SQL-Server:如何使用数据透视表来获得结果?

时间:2012-05-05 06:47:21

标签: sql sql-server-2005 pivot-table

我有下表

DECLARE @sample TABLE
(
    ColNam varchar(20),
    C1  int
)


INSERT INTO @sample
SELECT   'Admin', 1 UNION ALL
SELECT  'Admin', 4  UNION ALL
SELECT   'Admin', 7     UNION ALL
SELECT   'NUser', 3 UNION ALL
SELECT  'NUser', 6  UNION ALL
SELECT   'NUser', 8  

SELECT * FROM @sample

我想获得以下格式:

Admin | 1 | 4 | 7
NUser | 3 | 6 | 8

All 1,4,7,3,6,8 can be variables . 

我可以使用哪种方法来获得该结果?数据透视表? 哪种方法更好?

请帮帮我。

提前致谢!

2 个答案:

答案 0 :(得分:1)

DECLARE @sample TABLE
(
    ColNam varchar(20),
    C1  int
)


INSERT INTO @sample
SELECT   'Admin', 1 UNION ALL
SELECT  'Admin', 4  UNION ALL
SELECT   'Admin', 7  

SELECT  * 
FROM 
(
    SELECT  ColNam,C1
    FROM    @sample
) A
PIVOT
(
    SUM(C1) FOR C1 IN([1],[4],[7])
) PVT


--OR you might need this

SELECT   CAST(ColNam AS VARCHAR(100)) + ' | ' + CAST([1] AS VARCHAR(100) )+  ' | ' + CAST([4] AS VARCHAR(100))+  ' | ' + CAST([7] AS VARCHAR(100))
FROM 
(
    SELECT  ColNam,C1
    FROM    @sample
) A
PIVOT
(
    SUM(C1) FOR C1 IN([1],[4],[7])
) PVT

答案 1 :(得分:0)

感谢您的回复。我通过以下代码得到了我想要的结果:

-- Create Table 
CREATE TABLE tbl_sample (ColNam varchar(20),C1 int)

-- Insert Data
INSERT INTO tbl_sample
SELECT   'Admin', 1 UNION ALL
SELECT  'Admin', 4  UNION ALL
SELECT   'Admin', 7 UNION ALL
SELECT   'NUser', 1 UNION ALL
SELECT  'NUser', 5  UNION ALL
SELECT   'NUser', 4 

-- Because my C1 column can be variable so I create dynamic like following
DECLARE @PivotColumnHeaders VARCHAR(MAX)
SELECT @PivotColumnHeaders =
 COALESCE(
    @PivotColumnHeaders + ',[' + cast(C1 as varchar) + ']',
    '[' + cast(C1 as varchar)+ ']'
  )
  FROM tbl_sample
  GROUP BY C1

-- Then Select like following  
DECLARE @PivotTableSQL NVARCHAR(MAX)
SET @PivotTableSQL = N'
  SELECT *
  FROM (
    SELECT  ColNam,C1
    FROM    tbl_sample
  ) AS PivotData
  PIVOT (
    MAX(C1)
    FOR C1 IN (
      ' + @PivotColumnHeaders + '
    )
  ) AS PivotTable
'

EXECUTE(@PivotTableSQL)

我得到了我想要的结果。再次感谢大家。

我引用此网站 Dynamic Pivot Table Queries in SQL

红色