简体   繁体   中英

mysql sum, CASE WHEN with GROUP BY

In MySQL, I want to sum the values ​​of certain statuses and display them in the same count column,

Do I have to give a condition to count ?!

status is 0, 1, 2 and 3, and status = 2 is a sum of 2, 3, 4 count values.

What kind of conditions should I give?

My Query:

SELECT A.STATUS, B.COUNT, B.REG_DT FROM 
(SELECT 0 AS STATUS UNION ALL  SELECT 1 UNION ALL  SELECT 2 UNION ALL  SELECT 3 UNION ALL  SELECT 4) A
   LEFT JOIN (
      SELECT STATUS , COUNT(*) AS COUNT, FROM TB_EXE WHERE reg_dt >=  CURDATE() 
      GROUP BY STATUS
) B ON A.STATUS = B.STATUS

My Data:

  status |  count           
 -----------------      
    0    |    1         
 -----------------      
    1    |    2         
 -----------------      
    2    |    1         
 -----------------
    3    |    0
 -----------------
    4    |    2

Expected Results:

  status |  count
 -----------------
    0    |    1
 -----------------
    1    |    2
 -----------------
    2    |    3

you can try like below using case when

select case when status>1 then 2 else status end as status,
sum(count) as cnt from t
group by status
SELECT STATUS,COUNT(*)
 FROM T
 WHERE STATUS < 2
 GROUP BY STATUS
 UNION ALL
 (SELECT 2,COUNT(*)
 FROM T
 WHERE STATUS >= 2
  ) 

Where the 2 aggregations are dealt with separately.

+--------+----------+
| STATUS | COUNT(*) |
+--------+----------+
|      0 |        1 |
|      1 |        1 |
|      2 |        3 |
+--------+----------+
3 rows in set (0.00 sec)

Or more succinctly

 select case when status > 1 then 2 else status end, count(*)
  from t
  group by case when status > 1 then 2 else status end

Hmmm, I think I'd go with a framing solution on this one. IE something like this:

SELECT 
  Status,
  Count,
  SUM(Count) OVER(ORDER BY status ROWS
       BETWEEN UNBOUNDED PRECEDING
       AND CURRENT ROW) AS FramedCount
FROM Status

this gives you a running total of the counts from all previous rows as the framed count. You can handle the logic in the application to determine which statuses should use the framed count OR you could handle it in the query by adding the following.

SELECT 
  status,
  CASE
    when status <= 3 THEN count
    ELSE SUM(count) OVER(ORDER BY status ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
    END AS 'MyCount'
FROM statusInfo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM