需要数据统计页面,肯定需要导出数据,于是,边学边写,完成了一段sql~
最早的版本是这样的:分三条sql查出三种不同的状态的记录数(总记录,未支付,已支付)文章源自IT老刘-https://itlao6.com/786.html
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函数,于是变成了:文章源自IT老刘-https://itlao6.com/786.html
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出现了:文章源自IT老刘-https://itlao6.com/786.html
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老五文章源自IT老刘-https://itlao6.com/786.html
文章源自IT老刘-https://itlao6.com/786.html文章源自IT老刘-https://itlao6.com/786.html相关报表图形绘制:统计报表 -- HignCharts:线形图饼图绘制及时间等定制文章源自IT老刘-https://itlao6.com/786.html
继续阅读
我的微信公众号
微信扫一扫关注公众号,不定时更新
评论