统计报表 -- sql统计语句

需要数据统计页面,肯定需要导出数据,于是,边学边写,完成了一段sql~

9166166-14b91dae0506d09d.jpg
统计报表 -- sql统计语句

最早的版本是这样的:分三条sql查出三种不同的状态的记录数(总记录,未支付,已支付)

SELECT COUNT(*) AS RecordCount FROM t_record WHERE CreateTime >= '2019-01-01 00:00:00'  AND CreateTime < '2019-02-01 00:00:00' 
SELECT COUNT(*) AS UnPayedCount FROM t_record WHERE CreateTime >= '2019-01-01 00:00:00'  AND CreateTime < '2019-02-01 00:00:00' AND IsPayed = 0
SELECT COUNT(*) AS PayedCount FROM t_record WHERE CreateTime >= '2019-01-01 00:00:00'  AND CreateTime < '2019-02-01 00:00:00' AND IsPayed = 1 

但是,还有一个需求,对记录数进行分日期进行统计,于是,需要改进,想到了用 GROUP BY 去实现; 但问题是CreateTime是DateTime, 接着百度之,找到了 CONVERT函数,于是变成了:

SELECT COUNT(*) AS RecordCount FROM t_record WHERE CreateTime >= '2019-01-01 00:00:00'  AND CreateTime < '2019-02-01 00:00:00' GROUP BY CONVERT(CreateTime,DATE)
SELECT COUNT(*) AS UnPayedCount FROM t_record WHERE CreateTime >= '2019-01-01 00:00:00'  AND CreateTime < '2019-02-01 00:00:00' AND IsPayed = 0 GROUP BY CONVERT(CreateTime,DATE)
SELECT COUNT(*) AS PayedCount FROM t_record WHERE CreateTime >= '2019-01-01 00:00:00'  AND CreateTime < '2019-02-01 00:00:00' AND IsPayed = 1 GROUP BY CONVERT(CreateTime,DATE)

但是,为什么不能一条sql查出来呢?这样在便利性还是性能上应该都会有所提升,能否在COUNT带条件或者在SUM做判断?于是,最终的sql出现了:

SELECT 
    CONVERT(CreateTime,DATE) AS RecordDate,
    COUNT(*) AS RecordCount, 
    SUM(CASE WHEN IsPayed = 0 THEN 1 ELSE 0 END) AS UnPayedCount,
    SUM(CASE WHEN IsPayed = 0 THEN 1 ELSE 0 END) AS PayedCount,
FROM t_record 
    WHERE CreateTime >= '2019-01-01 00:00:00'  AND CreateTime < '2019-02-01 00:00:00'
GROUP BY CONVERT(CreateTime,DATE)

原文:简书ThinkinLiu 博客: IT老五

相关报表图形绘制:统计报表 -- HignCharts:线形图饼图绘制及时间等定制

9166166-931fd471780b7e64.jpg
IT老五(it-lao5):关注公众号,一起源创,一起学习!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

flybirding10011

谢谢支持啊999

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值