如何列出一年中的记录,从1月到12月甚至是空

时间:2016-07-22 04:54:32

标签: mysql

我正在做一份报告,让用户输入年份和股票代码。该报告将显示用户从选定年份的1月到12月的项目的月销售额。即使数据不存在,结果也必须为12个月。

set @yyyy = 2016;

select date_format(bb.bill_date, '%m/%y') as date_1, sum(bb.Qty), stockcode
from
(
select  1 as srce, zz.qty Qty, zz.stkcode stockcode, ll.bill_date bill_date 
FROM posbila ll, posbilb zz

WHERE 
    ll.bill_no = zz.receive_ID 
    AND 
    zz.stkcode >= '0' 
    AND 
    zz.stkcode <= 'zz' 
    AND 
    date_format(ll.billdate,"yyyy") = 2016

group by zz.StkCode, ll.bill_date
union select 2, 0, concat(@yyyy,'-01-31') 
union select 2, 0, concat(@yyyy,'-02-01') 
union select 2, 0, concat(@yyyy,'-03-31')
union select 2, 0, concat(@yyyy,'-04-30') 
union select 2, 0, concat(@yyyy,'-05-31') 
union select 2, 0, concat(@yyyy,'-06-30')
union select 2, 0, concat(@yyyy,'-07-31') 
union select 2, 0, concat(@yyyy,'-08-31') 
union select 2, 0, concat(@yyyy,'-09-30')
union select 2, 0, concat(@yyyy,'-10-31') 
union select 2, 0, concat(@yyyy,'-11-30') 
union select 2, 0, concat(@yyyy,'-12-31') 
) as bb

left join icstk kk on bb.stockcode = kk.stockcode

Group By 1, date_1

I have this query :
date_1    stkcode   Qty   stockcode    description
02/16     COKE      13    COKE         COKE123
03/16     COKE      112   COKE         COKE123
04/16     COKE      6     COKE         COKE123
06/16     COKE      5     COKE         COKE123

但我想要的是:

date_1    stkcode   Qty   stockcode    description
01/16               0
02/16     COKE      13    COKE         COKE123
03/16     COKE      112   COKE         COKE123
04/16     COKE      6     COKE         COKE123
05/16               0
06/16     COKE      5     COKE         COKE123
07/16               0
08/16     COKE      5     COKE         COKE123
09/16               0
10/16               0
11/16     COKE      15    COKE         COKE123
12/16     COKE      25    COKE         COKE123

1 个答案:

答案 0 :(得分:1)

You can add JAN to DEC month entry in tempTable and left join that table with your statement