用于更改表结构的SQL脚本

时间:2013-08-10 19:20:14

标签: sql sql-server-2008

我正在研究SQL数据库(Microsoft SQL Server 2008)

我有一张这样的表

Country     Gender           Number         
---------+---------------+-----------+
Russia       Male              50000                
Russia       Female            40000 
Russia       Unknown           30000
India        Male              45678                
India        Female            21354  
China        Male              37878                
China        Female            45686
China        Unknown           24534
France       Male              45378                
France       Female            49783   

是否有一个sql select脚本可以返回这样的表:

    Country      Male             Female      Unknown   
---------+---------------+-----------+-----------------+
Russia       50000            40000        30000             
India        45678            21354        0
China        37878            45686        24534
France       45378            49783        0

请注意,某些国家/地区没有“未知”数据,因此在这种情况下,数据应为0。

我尝试了几件事,但我没有得到任何接近的结果。谢谢你的帮助。

2 个答案:

答案 0 :(得分:2)

您可以使用pivot运算符进行此类查询:

select Country,
    IsNull([Male], 0) Male,
    IsNull([Female], 0) Female,
    IsNull([Unknown], 0) Unknown
from TableName t
   pivot (sum(Number) for Gender in ([Male], [Female], [Unknown])) p

... pivot max(Number) for ...如果您知道(Country, Gender)组合在原始数据中是唯一的。

答案 1 :(得分:1)

您也可以使用此查询

select
    T.Country,
    max(case when T.Gender = 'Male' then T.Number else 0 end) as Male,
    max(case when T.Gender = 'Female' then T.Number else 0 end) as Female,
    max(case when T.Gender = 'Unknown' then T.Number else 0 end) as Unknown
from Table1 as T
group by T.Country

sql fiddle demo