我不擅长创建查询。你能帮我安排一下这个问题吗?
Select Height, Country
CASE when Country = 'INDIA' then SUM(QTY) WHERE Country = 'INDIA' end as INDIA,
CASE when Country = 'JAPAN' then SUM(QTY) WHERE Country = 'JAPAN' end as JAPAN
from tb_Master
我想根据各自国家/地区选择每个人身高的SUM(数量)。数量代表人数或人口
Height INDIA JAPAN
4.5 120 90
5.0 40 30
5.3 60 70
答案 0 :(得分:0)
create table #tb_Master (height decimal(2,1), country varchar(6))
set nocount on
declare @i tinyint = 120
while @i>0
begin
insert #tb_Master values (4.5,'INDIA')
select @i -=1
end
set @i = 90
while @i>0
begin
insert #tb_Master values (4.5,'JAPAN')
select @i -=1
end
set @i = 40
while @i>0
begin
insert #tb_Master values (5.0,'INDIA')
select @i -=1
end
set @i = 30
while @i>0
begin
insert #tb_Master values (5.0,'JAPAN')
select @i -=1
end
set @i = 60
while @i>0
begin
insert #tb_Master values (5.3,'INDIA')
select @i -=1
end
set @i = 70
while @i>0
begin
insert #tb_Master values (5.3,'JAPAN')
select @i -=1
end
--select * from #tb_Master
select * from
(
select height, country, count(height) AS QTY
from #tb_Master
group by height, country
) AS table_source
PIVOT
(
SUM(QTY)
for country in ([INDIA], [JAPAN])
) AS table_alias
Print 'I suspect you will next want to perform a search for "dynamic pivot"'
drop table #tb_Master