Groupby使用PIVOT

时间:2013-08-23 15:29:57

标签: sql sql-server-2008 pivot

我有这张桌子:

Person  Job
PersonA XX
PersonA XX
PersonA XX
PersonB XX
PersonB XX
PersonB YY
PersonB ZZ
PersonC XX
PersonC XX
PersonA XX
PersonA YY
PersonB ZZ
...

现在,我希望输出是这样的:

Job PersonA PersonB Person C
XX  4       2       2
YY  1       1       0
ZZ  0       2       0

到目前为止,我有这个:

SELECT DISTINCT Person,
                       (SELECT COUNT(Job)
                        FROM dbo.TableName
                        GROUP BY Job)
FROM dbo.ExcelImport

没有运气:(

4 个答案:

答案 0 :(得分:3)

你应该尝试这样的事情:

select
    Job
    ,SUM(case when Person = 'PersonA'
        then
            1
        else
            0
    end) as 'PersonA'
    ,SUM(case when Person = 'PersonB'
        then
            1
        else
            0
    end) as 'PersonB'
    ,SUM(case when Person = 'PersonC'
        then
            1
        else
            0
    end) as 'PersonC'
from
    TableName
group by
    Job

答案 1 :(得分:2)

pivot运营商很容易完成任务:

select *
from (select Job as Job2, * from [TableName]) t
    pivot (count(Job2) for Person in ([PersonA],[PersonB],[PersonC])) p

答案 2 :(得分:0)

你也可以使用支点

select * from per
pivot (count(job)  for job in ([xx],[yy],[zz]))

答案 3 :(得分:0)

如果有人被修复,请尝试此操作

SELECT * FROM Table1
PIVOT
(
    COUNT([Person]) FOR [Person] IN ([PersonA],[PersonB],[PersonC])
) p

SQL FIDDLE DEMO

如果有不同的人,请尝试此动态查询

DECLARE @cols AS NVARCHAR(MAX), @query  AS NVARCHAR(MAX)
SELECT @cols = STUFF((SELECT distinct ',' + QUOTENAME([Person]) 
                    from Table1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

SET @query = 'SELECT [Job],' + @cols + ' 
             FROM
             (
                Select *
                FROM Table1
             ) T
             PIVOT
             (
                COUNT([Person])
                FOR [Person] IN (' + @cols + ')
             ) pvt '

EXECUTE(@query);