简体   繁体   中英

How to select a row depending on if exist case in SQL Server?

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.

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

Demo here

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM