php计算数据值,php – 计算数据表并对其求和,并使用默认值填充空数据

我有一个只包含日期数据的表,我想计算数据在同一个月的次数,并且对于那个问题它已经完成了,现在我得到一个新问题,即缺少的月份,这是因为这个月没有数据.现在我想添加默认值为0的空月,即使月份不在表中.任何人都可以根据我的查询帮助我吗?

这是我的数据

start_date |end_date

------------------------

2018-10-01 |2018-10-02

2018-01-04 |2018-02-04

2018-08-01 |2018-10-01

这是我的疑问

select month(month_table) as month_table

, sum(cstart) as cstart

, sum(cend) as cend

from

(

(select `start_date` as month_table

, 1 as cstart

, 0 as cend

from newdata

)

union all

( select `end_date`

, 0

, 1

from newdata

)

) dd

group

by monthname(month_table)

, month(month_table)

order

by month(month_table)

结果是

month_table|cstart|cend

1 | 1 | 0

2 | 0 | 1

8 | 1 | 0

10 | 1 | 2

我想添加新的查询,所以我的结果将是

month_table|cstart|cend

1 | 1 | 0

2 | 0 | 1

3 | 0 | 0

4 | 0 | 0

5 | 0 | 0

6 | 0 | 0

7 | 0 | 0

8 | 1 | 0

9 | 0 | 0

10 | 1 | 2

11 | 0 | 0

12 | 0 | 0

最佳答案 你需要一个包含所有月份的桌子.您可以使用UNION ALL使用子查询创建一个ad hoc.然后将count子查询连接到该表.

SELECT m.month month_table,

coalesce(s.count, 0) cstart,

coalesce(e.count, 0) cend

FROM (SELECT 1 month

UNION ALL

SELECT 2 month

UNION ALL

SELECT 3 month

UNION ALL

SELECT 4 month

UNION ALL

SELECT 5 month

UNION ALL

SELECT 6 month

UNION ALL

SELECT 7 month

UNION ALL

SELECT 8 month

UNION ALL

SELECT 9 month

UNION ALL

SELECT 10 month

UNION ALL

SELECT 11 month

UNION ALL

SELECT 12 month) m

LEFT JOIN (SELECT month(n.start_date) month,

count(*) count

FROM newdata n

GROUP BY month(n.start_date)) s

ON s.month = m.month

LEFT JOIN (SELECT month(n.end_date) month,

count(*) count

FROM newdata n

GROUP BY month(n.end_date)) e

ON e.month = m.month

ORDER BY m.month;

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值