2014-05-23 53 views
0

我認爲這應該很簡單,但我不知道如何去做。如何爲每列使用不同的WHERE子句

我想編寫一個SQL查詢,它將輸出三列:星期,蘋果數量和橙子數量。

說我的數據庫看起來是這樣的:

week    | fruit_type | fruit_num 
------------------------------------------ 
6/17/2013 0:00:00 | Apples  | 4 
6/17/2013 0:00:00 | Oranges | 3 
6/24/2013 0:00:00 | Oranges | 1 
6/24/2013 0:00:00 | Apples  | 2 
6/24/2013 0:00:00 | Apples  | 7 

我想查詢輸出這樣的:

week    | Apples | Oranges 
------------------------------------------ 
6/17/2013 0:00:00 | 4  | 3 
6/24/2013 0:00:00 | 9  | 1 

我能得到蘋果和橘子分別是這樣的:

select 
date_trunc('week',week) as "Week", 
sum(fruit_type) as "Apples" 
from table 
where fruit_type = 'Apples' 
group by date_trunc('week',week) 
order by date_trunc('week',week) 

但顯然更喜歡用相同的查詢生成兩列。

回答

2

我不知道的,所以我留下什麼date_trunc了這一點。你應該使用 -

http://sqlfiddle.com/#!2/69bfb/2

+0

建議您也在'WHERE fruit_type IN('Apples','Oranges')'給優化器一個鏡頭。可能會有更多的成果,而你只關心這個查詢中的那兩個。 – woot

1

你可以使用case語句。您在執行選擇時應用條件,因此不需要where子句。

SELECT 
date_trunc('week',week) as "Week", 
[Apples] = SUM(CASE WHEN fruit_type = 'Apples' THEN fruit_num END), 
[Oranges] = SUM(CASE WHEN fruit_type = 'Oranges' THEN fruit_num END) 

FROM 
table 

GROUP BY ... 
0
select 
date_trunc('week',week) as "Week", 
CASE WHEN fruit_type = 'Apples' THEN sum(fruit_type) as "Apples", 
CASE WHEN fruit_type = 'oranges' THEN sum(fruit_type) as "Oranges" 
from table 
group by date_trunc('week',week) 
order by date_trunc('week',week) 
+0

「喜歡」是不必要的:

SELECT week, SUM(CASE WHEN fruit_type = 'Apples' THEN fruit_num END) as 'Apples', SUM(CASE WHEN fruit_type = 'Oranges' THEN fruit_num END) as 'Oranges' from fruit group by week order by week 

例如:您可以通過SUM與CASE結合使用JOIN命令連接查詢,或做它用單查詢'='代替。使用通配符時只需要LIKE。 –

+0

是的,如果有些人輸入數據與錯字它會很有用。 –

+0

不是沒有指定通配符,它​​不是。它不會匹配沒有通配符的'Apples2',即使有LIKE;你需要像'蘋果%'或'蘋果_'這樣的工作。 (當然,除非在MySQL允許的非標準,奇怪的語法允許它工作,在這種情況下,還有一個理由來避免MySQL。) –