0

这可能很容易,但我已经搜索了文档并且无法弄清楚。这是源表:

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;

任何帮助表示赞赏;谢谢!

4

1 回答 1

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;
于 2013-08-26T17:14:55.573 回答