0

我有下表

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 . 

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

请帮我。

提前致谢!

4

2 回答 2

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
于 2012-05-05T10:55:48.557 回答
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)

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

我在 SQL 中引用了这个站点 Dynamic Pivot Table Queries

红军

于 2012-05-05T17:35:03.067 回答