1

我正在开发一个 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 选择脚本可以返回这样的表:

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

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

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

4

2 回答 2

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)组合在原始数据中是唯一的。

于 2013-08-10T19:25:51.630 回答
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 小提琴演示

于 2013-08-10T20:39:16.327 回答