下面是我的桌子,人口是每个城市的人口。
City state country population
c1 s1 co1 100000
c2 s1 co1 100000
c3 s1 co1 100000
c11 s2 co1 100000
c12 s2 co1 100000
我需要如下输出
s1 300000
s2 200000
co1 500000
任何人都可以使用sql server或Teradata帮助实现这一目标
答案 0 :(得分:1)
您可以使用apply
:
select col, sum(population)
from table t cross apply
( values (state, population), (country, population)
) tt(col, population)
group by col;
您还可以将union all
用于其他DBMS:
select t.state, sum(t.population)
from table
group by t.state
union all
select t.country, sum(t.population)
from table
group by t.country;
答案 1 :(得分:1)
apply如yogesh所说的那样工作,但这可能更容易理解
select 'state' as t, state as s, sum(population) as total
from table_you_did_not_name
group by state
union all
select 'country' as t, country as s, sum(population) as total
from table_you_did_not_name
group by country
答案 2 :(得分:0)
您需要2个不同的分组,然后将它们与UNION组合:
select state column1, sum(population) column2
from tablename
group by state
union all
select country, sum(population)
from tablename
group by country
答案 3 :(得分:0)
一个简单的解决方案是合理地计算它们并结合在一起
select state, sum(population)
from table
group by state
union all
select country, sum(population)
from table
group by country