Sql server 在某些条件下使用Sum
我说了以下几行Sql server 在某些条件下使用Sum,sql-server,sql-server-2008,tsql,Sql Server,Sql Server 2008,Tsql,我说了以下几行 Country Population IE 30 IE 20 UK 15 DE 20 DE 10 UK 20 BE 5 所以基本上我只想把IE和DE的值加起来。。。剩下的我只想要值 所以这就是所有这些的总和 Select Country, Sum(Population) From CountryPopulation group by Country 我可以添加一个where子句来排除除IE和DE之外的所有其他国家。。。但我也希望在结果集中包含这些,但不要求和 所
Country Population
IE 30
IE 20
UK 15
DE 20
DE 10
UK 20
BE 5
所以基本上我只想把IE和DE的值加起来。。。剩下的我只想要值
所以这就是所有这些的总和
Select Country, Sum(Population) From CountryPopulation group by Country
我可以添加一个where子句来排除除IE和DE之外的所有其他国家。。。但我也希望在结果集中包含这些,但不要求和
所以上面的表格加起来是这样的
Country Population
IE 50 -- Summed
UK 15 -- Orginal Value
DE 30 -- Summed
UK 20 -- Orginal Value
BE 5 -- Orginal Value
问题是我无法得到一个总和if,或者case,因为查询必须按groupby进行聚合。我唯一能做的事就是
对所有IE求和,并将其与其余数据反并。或
也许用CTE 有没有一种巧妙的方法可以做到这一点
Select Country, Sum(Population)
From CountryPopulation
group by case when Country in ('IE','DE')
then 'IE_DE'
else Country
end
产生:
Country rn
------- -------------------- -----------
BE 1 5
DE 1 30
IE 1 50
UK 6 15
UK 7 20
诀窍是只为每一行引入一个唯一的值,除了
IE
和DE
行都得到1
。如果源行all实际上已经具有这样一个唯一的值,那么可以简化CTE(或避免CTE,代价是必须将大小写
表达式放置在GROUP BY
以及SELECT
)您还可以使用UNION all
并将此查询分成两部分:
SELECT P.country,
P.population
FROM (SELECT country,
Population = Sum(population)
FROM dbo.countrypopulation cp
WHERE country IN ( 'IE', 'DE' )
GROUP BY country
UNION ALL
SELECT country, population
FROM dbo.countrypopulation cp
WHERE country NOT IN ( 'IE', 'DE' )
) P
ORDER BY P.population DESC
即使这不是那么简洁,它也是可读和高效的
我认为OP不想将
IE
和DE
的总和合并在一起-我认为他们只需要一行IE
,一行DE
,然后所有其他国家的行数应该与源表中的行数一样多。这是正确的Damien。。。我想把它们按国家加起来,而不是把它们加起来。。。但就像本案中的团队理念一样;-)谢谢蒂姆。。。是的,这是我唯一能想到的方法,但我讨厌重复SQL,我想看看有没有更技术性的解决方案。。。再次感谢
SELECT P.country,
P.population
FROM (SELECT country,
Population = Sum(population)
FROM dbo.countrypopulation cp
WHERE country IN ( 'IE', 'DE' )
GROUP BY country
UNION ALL
SELECT country, population
FROM dbo.countrypopulation cp
WHERE country NOT IN ( 'IE', 'DE' )
) P
ORDER BY P.population DESC