统计报表 — sql统计语句

  • 1,770 views
  • 阅读模式

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

统计报表 — sql统计语句
统计报表 -- 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:线形图饼图绘制及时间等定制

weinxin
我的微信公众号
微信扫一扫关注公众号,不定时更新
Liu, Thinkin
  • 本文由 发表于 2019-02-25 13:24:49
  • 转载请务必保留本文链接:https://itlao5.com/786.html
评论  0  访客  0
匿名

发表评论

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定