1

我有这张桌子:

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

4 回答 4

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
于 2013-08-23T15:36:35.710 回答
2

这对操作员来说很容易pivot

select *
from (select Job as Job2, * from [TableName]) t
    pivot (count(Job2) for Person in ([PersonA],[PersonB],[PersonC])) p
于 2013-08-23T15:40:08.773 回答
0

你也可以使用枢轴

select * from per
pivot (count(job)  for job in ([xx],[yy],[zz]))
于 2013-08-23T15:44:13.010 回答
0

如果人是固定的,试试这个

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

SQL 小提琴演示

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

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);
于 2013-08-24T06:24:12.750 回答