mysql sum,使用group by时为大小写

yhuiod9q  于 2021-06-17  发布在  Mysql
关注(0)|答案(3)|浏览(323)

在mysql中,我想对这些值求和​​并显示在同一计数列中,
我必须给一个条件来计数吗?!
status是0、1、2和3,status=2是2、3、4个计数值的总和。
我应该给什么样的条件?
我的问题:

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

我的数据:

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

预期结果:

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

g6baxovj1#

您可以在以下情况下尝试使用case

select case when status>1 then 2 else status end as status,
sum(count) as cnt from t
group by status
yzxexxkh

yzxexxkh2#

嗯,我想我应该用一个框架解决这个问题。例如:

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

这将为您提供所有前一行的运行总数作为帧计数。您可以在应用程序中处理逻辑,以确定哪些状态应使用框架计数,也可以在查询中通过添加以下内容来处理它。

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
ckx4rj1h

ckx4rj1h3#

SELECT STATUS,COUNT(*)
 FROM T
 WHERE STATUS < 2
 GROUP BY STATUS
 UNION ALL
 (SELECT 2,COUNT(*)
 FROM T
 WHERE STATUS >= 2
  )

其中两个聚合分别处理。

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

或者更简洁

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

相关问题