2016-08-31 185 views
3

我有選擇分組的例子:動態WHERE子句

SELECT cod, value, type 
FROM table 
GROUP BY cod, value, type 

我得到的結果:

cod | value | type 
1 | 1000 | A 
1 | 570 | B 
2 | 2000 | A 
3 | 1500 | A 
3 | 200 | B 

但僅cod = 1應從type = A返回值。期望的結果:

cod | value | type 
1 | 1000 | A 
2 | 2000 | A 
3 | 1500 | A 
3 | 200 | B 

我認爲CASE聲明WHERE,但有侷限性,不能正常工作。我怎麼能做到這一點?

WHERE CASE WHEN cod = 1 THEN type = 'A' END 
+0

對於所有'cod = 1',你想要將類型任意設置爲A還是要排除type = A和cod <> 1'的數據? –

+0

我只想從'cod = 1'獲得'type = A'的值。 –

回答

1
WHERE Type = CASE WHEN cod = 1 THEN 'A' else Type END 
+0

返回'='附近的語法不正確' –

+0

First = or 2nd or 3rd? – artm

+0

2nd,在'THEN' –

2

給你:

SELECT cod, value, type 
FROM table 
WHERE cod != 1 OR type='A' 
GROUP BY cod, value, type 
0

另一個不錯的選擇 - 不,但最好的方式在這裏一個有用的選項。

SELECT cod, value, type 
FROM table 
GROUP BY cod, value, type 

EXCEPT 

SELECT cod, value, type 
FROM table 
WHERE cod = 1 AND type <> 'A' 
GROUP BY cod, value, type