如何根据SQL Server中是否存在的情况选择一行?

时间:2017-02-21 07:52:20

标签: sql sql-server

我想选择具有特定品牌的商品,如果品牌未包含在表格中,请选择具有品牌名称的商品' all'。我有这样的table1:

Discount |  Brand
    20   |   ford
    10   |   all

我有一个名为@Brand_name的查询参数。如果存在于表格中,我想要的只是返回品牌的价格。否则返回品牌名称'全部'。这样做的正确查询是什么。谢谢你的帮助。

4 个答案:

答案 0 :(得分:7)

试试这个:

SELECT TOP 1 Discount
FROM mytable
WHERE Brand = @Brand_name OR Brand = 'all'
ORDER BY CASE 
            WHEN Brand = 'all' THEN 1
            ELSE 0 
         END

查询返回始终一条记录,因为选择了Brand = 'all'的记录,TOP 1子句中使用了SELECT

如果您有多个 'Brand'条记录并且您希望返回所有,则可以使用以下查询:

;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

答案 1 :(得分:2)

请试试这个:

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

答案 2 :(得分:0)

将此作为另一种解决方案添加,不确定这是否更好:

SELECT TOP 1 Discount FROM (
    SELECT Discount FROM table1 WHERE BrandName=@Brand_name
    UNION SELECT Discount FROM table1 WHERE BrandName='all'
) discount

答案 3 :(得分:0)

我采取不同的方法,我认为可以产生更好的效果:

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