如何选择用户所选年份的所有月份的数据甚至是空的

时间:2016-07-20 07:21:38

标签: mysql

我有2张桌子,posbila和posbilb。 字段bill_date(以dateTime格式存储)位于posbilb中的表posbila和字段Qty

我已经尝试了以下查询,但是没有显示空数据的月份

SELECT
    posbilb.stkcode,
    SUM(posbilb.qty),
    date_format(posbila.bill_date, '%m/%y')

FROM
    posbila,posbilb
WHERE
    posbila.bill_no = posbilb.RECEIVE_ID

GROUP BY 
    1, 3

如果用户选择2015年,我想要以下结果:

  

月|数量
  Janury | 154个
  二月| 00
  三月| 123个
  四月| 00
  五月| 00
  六月| 60个
  七月| 00
  八月| 99个
  九月| 00
  十月| 00
  十一月| 10个
  十二月| 00

1 个答案:

答案 0 :(得分:0)

如果您没有日期表并且没有创建日期表的权限,那么您可以联合我们。例如 给定

select * from tbl_loanledger;
+------+-------------+---------------+---------+---------+--------------+---------+
| id   | borrower_id | loanmaster_id | payment | balance | date_created | deleted |
+------+-------------+---------------+---------+---------+--------------+---------+
|    1 |           4 |             1 |      50 |     250 | 2016-05-28   |       0 |
|    2 |           1 |             2 |      20 |      80 | 2016-05-25   |       0 |
|    3 |           1 |             2 |      30 |      50 | 2016-06-01   |       0 |
|    4 |           2 |             3 |     100 |     400 | 2016-06-09   |       0 |
|    5 |           2 |             3 |      50 |     350 | 2016-06-10   |       0 |
|    6 |           1 |             4 |      50 |     200 | 2016-06-16   |       0 |
|    7 |           1 |             7 |      50 |     250 | 2016-06-16   |       1 |
+------+-------------+---------------+---------+---------+--------------+--------+

set @yyyy = '2016';

select      date_format(s.date_created, '%m/%y') 'mm/yy', sum(s.payment) amount
from
(
select  1 as srce,ll.payment payment, ll.date_created date_created from tbl_loanledger ll
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,'-07-31') union select 2, 0, concat(@yyyy,'-09-30')
union select 2, 0, concat(@yyyy,'-10-31') union select 2, 0, concat(@yyyy,'-09-30') union select 2, 0, concat(@yyyy,'-12-31') 
) s 
group       by 1

结果

+-------+--------+
| mm/yy | amount |
+-------+--------+
| 01/16 |      0 |
| 02/16 |      0 |
| 03/16 |      0 |
| 04/16 |      0 |
| 05/16 |     70 |
| 06/16 |    230 |
| 07/16 |      0 |
| 09/16 |      0 |
| 10/16 |      0 |
| 12/16 |      0 |
+-------+--------+