这可能很简单,但我已经仔细检查了文档,无法弄明白。这是源表:
store item date sales
101 00001 27-Oct-12 1
101 00002 27-Oct-12 0
102 00001 27-Oct-12 2
102 00002 27-Oct-12 1
101 00001 3-Nov-12 0
101 00002 3-Nov-12 0
102 00001 3-Nov-12 1
102 00002 3-Nov-12 1
...而且我正在尝试编写一个查询,最终得到一份月度销售表,商店有自己的列,例如,只有项目#00001 -
monthyear store101sales otherstoresales
10/2012 1 2
11/2012 0 1
这是我试过的代码 -
select distinct
year(date) as SalesYear,
month(date) as SalesMonth,
sum(case when store in (101) then sales.count else 0 end) as store101sales,
sum(case when store in (102,103) then sales.count else 0 end) as otherstoresales,
from source_table
where item=00001;
GROUP BY SalesYear, SalesMonth, store101sales, otherstoresales,
ORDER BY SalesYear, SalesMonth, store101sales, otherstoresales;
任何帮助表示感谢;谢谢!
答案 0 :(得分:1)
你很接近,不需要GROUP BY
聚合,也不确定MySQL是否允许在GROUP BY
中使用别名:
select year(date) as SalesYear,
month(date) as SalesMonth,
sum(case when store in (101) then sales else 0 end) as store101sales,
sum(case when store in (102,103) then sales else 0 end) as otherstoresales
from source_table
where item=00001;
GROUP BY year(date), month(date)
ORDER BY SalesYear, SalesMonth, store101sales, otherstoresales;