2015-09-17 2 views
0

Я плохо разбираюсь в создании запросов. Можете ли вы, ребята, помочь мне организовать этот запрос?SQL Query: используйте CASE в строковом значении и где статья

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 

Я хочу выбрать СУММУ (Кол-во) высоты каждого народа в соответствующих странах. КОЛ представляет число людей или население

Height INDIA JAPAN 
4.5 120 90 
5.0 40  30 
5.3 60  70 
+0

пожалуйста, вы можете предоставить схему tb_Master таблицы, что такое КОЛ ?? –

+0

Вы должны разместить 'CASE' внутри' SUM', например 'SUM (CASE WHEN Country = 'INDIA' THEN QTY ELSE 0 END) AS INDIA' –

+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 
Смежные вопросы