0

我希望单个 mysql 查询向以下查询添加一个新行,其中包含所有列值的总和值。请帮我

SELECT username,enddt,SUM(zerotothirty) AS 0To30,
SUM(thirtytosixty) AS 31To60,SUM(sixtytoonetwenty) AS 61To120,
SUM(onetwentytotwoforty) AS 121To240,SUM(greaterthantwoforty) AS '>240' 
FROM 
(SELECT username,DATE(enddt) AS enddt,tickid,
 IF(duration <=30, 1,0) zerotothirty,
 IF(duration BETWEEN 31 AND 60, 1,0) thirtytosixty,
 IF(duration BETWEEN 61 AND 120,1,0) sixtytoonetwenty,
 IF(duration BETWEEN 121 AND 240,1,0) onetwentytotwoforty,
 IF(duration >240,1,0) greaterthantwoforty
 FROM report)AS r
 GROUP BY username,DATE(enddt);
4

2 回答 2

1

Use the WITH ROLLUP modifier to GROUP BY:

GROUP BY username,DATE(enddt) WITH ROLLUP;

(In your case, this will show subtotals for each username, and a total for all results).

于 2012-05-11T06:58:01.897 回答
0

为了用汇总来补充 Eggyal 的答案,您可以通过将 IF() 求和简化为

SELECT 
      username,
      DATE(enddt) AS enddt,
      SUM( IF(duration <=30, 1,0 )) as 0To30,
      SUM( IF(duration BETWEEN 31 AND 60, 1,0 )) as 31To60,
      SUM( IF(duration BETWEEN 61 AND 120,1,0 )) as 61To120,
      SUM( IF(duration BETWEEN 121 AND 240,1,0 )) as 121To240,
      SUM( IF(duration >240,1,0)) as '>240'
   FROM 
      report
   GROUP BY 
      username,
      DATE(enddt)
   WITH ROLLUP
于 2012-05-11T13:05:52.800 回答