2015-10-23 144 views
0

我有以下表和數據:SQL - 條件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 

我想要做的是檢查,其中城市= '倫敦' AND ref ='GBP',如果沒有排位賽資格,那麼檢查一下這個城市是否是倫敦,ref是什麼,嘗試使用case但是沒有工作。

在這種情況下,我應該只得到行#1。

感謝

回答

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') 
1

剛剛回歸時,有沒有GPB行不包含GBP行,並使用NOT EXISTS

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

如果你正在處理一個記錄,那麼接下來應該工作:

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

什麼與關係? – lad2025

+0

默認情況下TOP 1不返回關係。 OP問題描述不是很清楚,我假定他總是隻想返回單排。 – Arvo

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' 

SELECTUNION後是有條件的地方。

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

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'))) 
+0

您的第二個解決方案不起作用:通過ID排序並不能保證GBP將成爲第一行(在這種情況下是的,但這肯定不會每次都是這種情況)。 –

+0

與ref相同,如果某種其他貨幣存在名稱,例如USD,該怎麼辦? –

0

我認爲你可以處理的情況下訂購像這樣

SELECT TOP 1 * 
FROM @Temp t 
    CROSS APPLY -- The ordering logic write here 
    (
     SELECT 
      CASE 
       WHEN (city = 'London' AND ref = 'GBP') THEN 1 
       WHEN (city = 'London' AND ref <> 'GBP') THEN 2 
       -- Not match at all 
      END AS Value 
    ) orders 
WHERE orders.Value IS NOT NULL 
ORDER BY 
    CASE WHEN orders.Value IS NULL THEN 1 ELSE 0 END, 
    orders.Value