我认为这应该很简单,但我不知道该怎么做。
我想编写一个输出三列的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)
但显然更愿意使用相同的查询生成两个列。
答案 0 :(得分:3)
我不确定date_trunc是什么,所以我把它排除在外。您可以使用JOIN命令来连接查询,也可以通过将SUM与CASE结合使用单个查询来执行:
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
示例:
答案 1 :(得分:1)
您可以使用案例陈述。您在执行select时应用条件,因此不需要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 ...
答案 2 :(得分: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)