所以我有一个事故表:
incidentID | threatlevel | typeOfIncident | region
__________________________________________________
1 5 H1N5 West
2 5 Zombie Apocalyse West
3 5 Zombie Apocalyse South
4 5 H1N5 North
5 5 Zombie Apocalyse East
6 3 Zombie Apocalyse West
如何根据2种不同类型的事件检索每个区域的威胁等级总和? 我尝试了GROUP BY区域,但它消除了所有类似的区域。
如何在单个SQL语句中检索所有这些值:
例如
来自北部地区的Zombie Apocalypse的总威胁等级为0, 来自南部地区的Zombie Apocalypse的总威胁等级为5,来自东部地区的Zombie Apocalypse的总威胁等级为5,
来自西部地区的Zombie Apocalypse的总威胁等级为8,
来自北部地区的H1N5总威胁等级为5,
来自南部地区的H1N5总威胁等级为0
来自Eastregion的H1N5的总威胁等级为0
来自西部地区的H1N5总威胁等级为5,
返回: 0 AS ZombieNorth,5 AS ZombieSouth,5 AS ZombieEast,8 ZombieWest,5 AS H1N5North,0 AS H1N5South,0 AS H1N5East,5 H1N5West,
答案 0 :(得分:2)
在任何数据库中,您可以使用GROUP BY
的两个键:
select typeOfIncident, region, sum(threatlevel) as total_threatlevel
from t
group by typeOfIncident, region;
答案 1 :(得分:0)
试试这个:
SELECT typeOfIncident,
SUM(CASE WHEN region = 'West' THEN threatlevel ELSE 0 END) AS WestThreatLevel,
SUM(CASE WHEN region = 'East' THEN threatlevel ELSE 0 END) AS EastThreatLevel,
SUM(CASE WHEN region = 'North' THEN threatlevel ELSE 0 END) AS NorthThreatLevel,
SUM(CASE WHEN region = 'South' THEN threatlevel ELSE 0 END) AS SouthThreatLevel
FROM mytable
GROUP BY typeOfIncident
SELECT
子句使用条件聚合来计算每个单独threatlevel
的{{1}}之和。
答案 2 :(得分:0)
您的问题中有以下内容让我感到困惑:
来自西部地区的Zombie Apocalypse的总威胁等级为8
...
来自西部地区的Zombie Apocalypse的总威胁等级为5
假设第二个应该是
来自西部地区的H1N5总威胁等级为5
然后我认为答案是
SELECT
region
,typeOfIncident
,SUM(threatLevel)
FROM
<table>
GROUP BY
region
,typeOfIncident
;