在sql中更改表的方向

时间:2013-08-06 05:12:52

标签: sql sql-server pivot

我的表格如下:

count  occupation  gender
800    engineer     M
400    engineer     F
700    doctor       M
100    doctor       F

我希望表格看起来像

 Gender  engineer doctor
   M     800      700
   F     400      100

我如何实现这一变化?

1 个答案:

答案 0 :(得分:2)

试试这个 -

<强>查询:

DECLARE @temp TABLE
(
      [count] INT
    , occupation VARCHAR(20)
    , gender CHAR(1)
)

INSERT INTO @temp ([count], occupation, gender)
VALUES 
    (800, 'engineer', 'M'),
    (400, 'engineer', 'F'),
    (700, 'doctor', 'M'),
    (100, 'doctor', 'F')

SELECT *
FROM @temp
PIVOT 
(
    SUM([count]) 
    FOR occupation IN ([engineer], [doctor])
) p
ORDER BY gender DESC

<强>输出:

gender engineer    doctor
------ ----------- -----------
M      800         700
F      400         100

更新#2:

<强>查询:

IF OBJECT_ID (N'tempdb.dbo.#temp') IS NOT NULL
   DROP TABLE #temp

CREATE TABLE #temp
(
      [count] INT
    , occupation VARCHAR(20)
    , gender CHAR(1)
)

INSERT INTO #temp ([count], occupation, gender)
VALUES 
    (800, 'engineer', 'M'),
    (400, 'engineer', 'F'),
    (700, 'doctor', 'M'),
    (100, 'doctor', 'F'),
    (100, 'tester', 'F'),
    (100, 'programmer', 'M'),
    (100, 'programmer', 'F'),
    (100, 'programmer', 'M')

DECLARE @cols NVARCHAR(MAX)

SELECT @cols = STUFF((
    SELECT DISTINCT ', [' + occupation + ']'
    FROM #temp
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, '')

DECLARE @SQL NVARCHAR(MAX)
SELECT @SQL = '
    SELECT *
    FROM #temp
    PIVOT 
    (
        SUM([count]) 
        FOR occupation IN (' + @cols + ')
    ) p
    ORDER BY gender DESC'

PRINT @SQL
EXEC sys.sp_executesql @SQL

<强>输出:

gender doctor      engineer    programmer  tester
------ ----------- ----------- ----------- -----------
M      700         800         200         NULL
F      100         400         100         100