繁体   English   中英

SQL有条件地应用求和平均值

[英]SQL apply sum avg conditionally

假设我们有下表:

index  value
1      55  
2      66  
3      77  
1      88  
3      99

在一个select语句中,如何在index = 1或index = 3时求和(值),在index = 2时求平均值(avg)?

容易:

SELECT index, CASE WHEN index IN (1, 3) THEN SUM(value) ELSE AVG(value) END
FROM yourTable
GROUP BY index
SELECT sum(value) as agg,
       'S' as aggregateType
FROM DaTAble
WHERE index IN (1, 3)

UNION ALL

SELECT avg(value) as agg,
       'A' as aggregateType
FROM DaTAble
WHERE index = 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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