SQL - 条件Where语句

时间:2015-10-23 08:41:40

标签: sql sql-server where

我有以下表格和数据:

DECLARE @Temp TABLE (id int, city varchar(10), ref varchar(10))

INSERT INTO @Temp (id, city, ref)
SELECT 1, 'London', 'GBP' UNION ALL
SELECT 2, 'London', 'EUR' 

SELECT  *
FROM    @Temp
WHERE ((city = 'London' AND ref = 'GBP') OR (city = 'London' AND ref <> 'GBP'))

返回:

1 London GBP
2 London EUR

我想做的是首先检查city ='London'和ref ='GBP'的位置,如果没有符合条件的行,那么请检查该城市是否为伦敦,ref可以是任何东西,尝试使用案例什么时候但不太有效。

在这种情况下,我应该只获得#1行。

由于

6 个答案:

答案 0 :(得分:1)

如果您正在处理单个记录,那么接下来应该有效:

SELECT  TOP 1 *
FROM    @Temp
WHERE city = 'London'
ORDER BY CASE WHEN ref = 'GBP' THEN 0 ELSE 1 END

答案 1 :(得分:1)

SELECT *
FROM @Temp
WHERE city = 'London' AND ref = 'GBP'
UNION
SELECT *
FROM @Temp
WHERE NOT EXISTS (
    SELECT * 
    FROM @Temp 
    WHERE city = 'London' AND ref = 'GBP'
) AND city = 'London'
SELECT之后

UNION是有条件的。

答案 2 :(得分:1)

您可以使用CASE WHEN

SELECT  *
FROM @Temp
WHERE 
  CASE
   WHEN city = 'London' AND ref = 'GBP' THEN 1
   WHEN city = 'London' AND ref <> 'GBP' AND NOT EXISTS(SELECT 1 FROM @Temp
                                                        WHERE city = 'London' 
                                                        AND ref = 'GBP') THEN 1
   ELSE 0
END = 1

LiveDemo

答案 3 :(得分:0)

select city, max(ref)
from @Temp
group by city

可选地

select city, ref
from @Temp t1
where t1.ref = 'GBP'
   or not exists (select 1 from @Temp t2
                  where t2.city = t1.city
                    and t2.ref = 'GBP')

答案 4 :(得分:0)

您可以尝试NOT EXISTS之类的内容:

SELECT  *
FROM    @Temp
WHERE ((city = 'London' AND ref = 'GBP') OR (city = 'London' AND ref <> 'GBP'
      AND NOT EXISTS (SELECT *
                      FROM  @Temp
                      WHERE city = 'London' AND ref = 'GBP')))

答案 5 :(得分:0)

我认为你可以像这样处理订购

@50