行值作为列并获取计数

时间:2013-12-20 07:29:41

标签: sql sql-server sql-server-2008 tsql

我有一个表AreaTable,它具有以下结构和数据:

Username    Area    Counter
-----------------------------
Pravin  Vskp       1    
anil    Hyd        3    
Pravin  Chennai    3
Ang     Vskp       1    
anil    Vskp       3    
Immi    Chennai    3

现在我希望数据显示为:

        VSKP    HYD   CHENNAI   
Pravin    1      0      3   
Anil      3      3      0
Ang       1      0      0    
Immi      0      0      3

我尝试了查询

SELECT *
FROM (  SELECT username, area,counter
        FROM AreaTable) AS ET
PIVOT(MIN(counter) FOR username IN (area) AS PT
你能帮帮我吗...

2 个答案:

答案 0 :(得分:0)

您应该使用PIVOT

 DECLARE @DataSource TABLE
(
     [UserName] NVARCHAR(128)
    ,[Area] NVARCHAR(128)
    ,[Counter] TINYINT
)

INSERT INTO @DataSource ([UserName], [Area], [Counter])
VALUES   ('Pravin','Vskp',1)
        ,('anil','Hyd',3)    
        ,('Pravin','Chennai',3)
        ,('Ang','Vskp',1)    
        ,('anil','Vskp',3)   
        ,('Immi','Chennai',3)

SELECT [UserName]
      ,COALESCE([Vskp],0) AS [Vskp]
      ,COALESCE([Hyd],0) AS [Hyd]
      ,COALESCE([Chennai],0) AS [Chennai]
FROM @DataSource DS
PIVOT
(
    MAX([Counter]) FOR [Area] IN ([Vskp], [Hyd], [Chennai])
) PVT

此查询的结果是

enter image description here

注意,如果[Area]列中不同值的计数不同,您应该检查动态数据透视的方式。 SO中有很多答案。

答案 1 :(得分:0)

试试这个,

select username,[VSKP],[HYD],[CHENNAI] from
(select username,area,counter from @t) as src
pivot( 
min(Counter) for Area in([VSKP],[HYD],[CHENNAI])
) as pvt