简体   繁体   English

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

[英]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 : 我有这样的table1:

Discount |  Brand
    20   |   ford
    10   |   all

And I have the query parameter named @Brand_name. 我有一个名为@Brand_name的查询参数。 All I want is returning the rate of the brand if exist in table. 如果存在于表格中,我想要的只是返回品牌的价格。 Otherwise return the rate with brand name 'all'. 否则返回品牌名称为“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. 查询总是返回一条记录,因为选择了Brand = 'all'记录,并且SELECT子句中使用了TOP 1

In case you have more the one 'Brand' records and you want all of them returned, then you can use the following query: 如果您有更多的 '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 在这里演示

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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