0

I have table which contains the ids like -

id
o1
o2
o3

now another table contains price for these ids based on the country like

id    country     price
o1    IND         11
o1    US          10
o1    default     9
o2    default     2
o3    UK          4
o3    default     3

basically i have to write a stored procedure where i will pass the region as parameter. for example if region is UK then i want select rows as follows if there is match then select the row otherwise default row.

id       country        price
o1       default        9
o2       default        2
o3       UK             4

Can you please suggest a good and efficient way of writing in SQL?

2 Answers 2

1

Use CROSS APPLY with TOP:

DECLARE @country VARCHAR(20) = 'UK'

SELECT  x.*
FROM tblId i
CROSS APPLY(
    SELECT TOP 1 *
    FROM tblPrice p
    WHERE
        p.id = i.id
        AND (p.country = @country OR p.country = 'default')
    ORDER BY
        CASE 
            WHEN p.country = 'default' THEN 1 
            ELSE 0
        END
)x
Sign up to request clarification or add additional context in comments.

Comments

0

One method uses two left joins:

select ids.id, coalesce(p.country, d.country) as country,
       coalesce(p.price, d.price) as price
from ids left join
     prices p
     on ids.id = p.id and p.country = @country left join
     prices d
     on d.country = 'default';

I think a more interesting method uses cross apply:

select p.*
from ids cross apply
     (select top 1 p.*
      from prices p
      where p.id = ids.id and p.country in (@country, 'default')
      order by (case when p.country = @country then 1 else 2 end)
     ) p;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.