Reputation: 43
I want to select an item with certain brand and if the brand is not included in the table select the item with brand name 'all'. I have the table1 like this :
Discount | Brand
20 | ford
10 | all
And I have the query parameter named @Brand_name. All I want is returning the rate of the brand if exist in table. Otherwise return the rate with brand name 'all'. What is the correct query for doing that. Thanks for any help.
Upvotes: 4
Views: 912
Reputation: 20489
I'd go for a different approach, which I think could yield better performance:
SELECT top 1 discount ,
brand
FROM
( SELECT discount ,
brand ,
selector ,
min(selector) over () [minselect]
FROM
( SELECT discount ,
brand ,
1 [selector]
FROM mytable
WHERE brand = 'ford'
UNION ALL
SELECT discount ,
brand ,
2 [selector]
FROM mytable WHERE brand = 'all' ) r
GROUP BY discount ,
brand ,
selector ) r
WHERE selector = minselect
ORDER BY discount DESC
Upvotes: 0
Reputation: 31
Adding this one as another solution, not sure though if this is better:
SELECT TOP 1 Discount FROM (
SELECT Discount FROM table1 WHERE BrandName=@Brand_name
UNION SELECT Discount FROM table1 WHERE BrandName='all'
) discount
Upvotes: 0
Reputation: 72175
Try this:
SELECT TOP 1 Discount
FROM mytable
WHERE Brand = @Brand_name OR Brand = 'all'
ORDER BY CASE
WHEN Brand = 'all' THEN 1
ELSE 0
END
The query returns always one record since record with Brand = 'all'
is selected and TOP 1
is used in the SELECT
clause.
In case you have more the one 'Brand'
records and you want all of them returned, then you can use the following query:
;WITH CTE AS (
SELECT Discount,
RANK() OVER (ORDER BY CASE
WHEN Brand = 'all' THEN 1
ELSE 0
END) AS rnk
FROM mytable
WHERE Brand = @Brand_name OR Brand = 'all'
)
SELECT Discount
FROM CTE
WHERE rnk = 1
Upvotes: 7
Reputation: 347
Try this please:
IF EXISTS (SELECT 1 FROM table1 WHERE Brand = @Brand_name)
BEGIN
SELECT Discount FROM table1 WHERE Brand = @Brand_name
END
ELSE
BEGIN
SELECT Discount FROM table1 WHERE Brand = 'all'
END
Upvotes: 2