我有以下工作查询,它总结了每个月的长度列数/值。
SELECT SUM(CASE WHEN DATE_FORMAT(tblcm.omActCompDate, '%m') = 1 THEN (tblcm.Lgth) ELSE 0 END) AS 'Jan',
SUM(CASE WHEN DATE_FORMAT(tblcm.omActCompDate, '%m') = 2 THEN (tblcm.Lgth) ELSE 0 END) AS 'Feb',
SUM(CASE WHEN DATE_FORMAT(tblcm.omActCompDate, '%m') = 3 THEN (tblcm.Lgth) ELSE 0 END) AS 'Mar',
SUM(CASE WHEN DATE_FORMAT(tblcm.omActCompDate, '%m') = 4 THEN (tblcm.Lgth) ELSE 0 END) AS 'Apr',
SUM(CASE WHEN DATE_FORMAT(tblcm.omActCompDate, '%m') = 5 THEN (tblcm.Lgth) ELSE 0 END) AS 'May',
SUM(CASE WHEN DATE_FORMAT(tblcm.omActCompDate, '%m') = 6 THEN (tblcm.Lgth) ELSE 0 END) AS 'Jun',
SUM(CASE WHEN DATE_FORMAT(tblcm.omActCompDate, '%m') = 7 THEN (tblcm.Lgth) ELSE 0 END) AS 'Jul',
SUM(CASE WHEN DATE_FORMAT(tblcm.omActCompDate, '%m') = 8 THEN (tblcm.Lgth) ELSE 0 END) AS 'Aug',
SUM(CASE WHEN DATE_FORMAT(tblcm.omActCompDate, '%m') = 9 THEN (tblcm.Lgth) ELSE 0 END) AS 'Sep',
SUM(CASE WHEN DATE_FORMAT(tblcm.omActCompDate, '%m') = 10 THEN (tblcm.Lgth) ELSE 0 END) AS 'Oct',
SUM(CASE WHEN DATE_FORMAT(tblcm.omActCompDate, '%m') = 11 THEN (tblcm.Lgth) ELSE 0 END) AS 'Nov',
SUM(CASE WHEN DATE_FORMAT(tblcm.omActCompDate, '%m') = 12 THEN (tblcm.Lgth) ELSE 0 END) AS 'Dec',
SUM(tblcm.Lgth) AS Total
给我以下内容:
Jan 13050
Feb 5200
Mar 48450
Apr 34041
May 38000
Jun 0
Jul 0
Aug 0
Sep 0
Oct 0
Nov 0
Dec 0
如何只获得大于零的AVG?
我也试过:avg(tblcm.Lgth = 0的情况,然后是null,否则tblcm.Lgth结束)作为m_Avg但也得到1825
我需要得到27748(这是1月至5月的总和,除以5个月)
答案 0 :(得分:1)
我很确定你需要一个子查询才能做到这一点。以下假设您的原始查询正确,因为已发布并按您所说的方式运行。这是未经测试的,你可能在你的问题中包含了更多细节,所以如果这不符合你的需要,现在就告诉我。
SELECT AVG(sumLgth) AS avgLgth, SUM(sumLgth) AS totalLgth,
SUM(CASE WHEN theMonth = 1 THEN (tbl.sumLgth) ELSE 0 END) AS 'Jan',
SUM(CASE WHEN theMonth = 2 THEN (tbl.sumLgth) ELSE 0 END) AS 'Feb',
...
FROM (
SELECT MONTH(omActCompDate) AS theMonth, SUM(lgth) AS sumLgth
FROM tblcm
GROUP BY MONTH(omActCompDate)
HAVING sumLgth > 0
) tbl