动态列值的透视

时间:2017-11-13 09:51:38

标签: sql sql-server pivot

May Some One请帮助我如何获得以下输出。 SQL SERVER 2008

CREATE TABLE #TABLE
(
[Generic Name] varchar(15),
[Description]varchar(15)
)

INSERT #TABLE

SELECT 'RESISTOR',  'POWER' UNION ALL
SELECT 'RESISTOR',  'Type' UNION ALL
SELECT 'RESISTOR',  'DESIGN' UNION ALL
SELECT 'RESISTOR',  'Material' 

每个通用名称,设计,材料,其他,Power和TYPE的结果作为列名称下的列的值为Desc1,Desc2 .... DescN

**Generic Name    DESC1   ,DESC2  ,DESC2, DESC4   
RESISTOR        POWER   , Type    DESIGN, Material**

2 个答案:

答案 0 :(得分:1)

以下是动态实现的方法:

CREATE TABLE T1
(
[Generic Name] varchar(15),
[Description]varchar(15)
)

INSERT T1

SELECT 'RESISTOR',  'POWER' UNION ALL
SELECT 'RESISTOR',  'Type' UNION ALL
SELECT 'RESISTOR',  'DESIGN' UNION ALL
SELECT 'RESISTOR',  'Material';



DECLARE @Cols NVARCHAR(MAX);
DECLARE @SQL NVARCHAR(MAX);
DECLARE @Sel NVARCHAR(MAX);

SET @Cols = STUFF((SELECT distinct ',' + QUOTENAME(T1.Description) 
            FROM T1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'');
SET @Sel = STUFF((SELECT distinct ',' + QUOTENAME(T1.Description) + ' AS DESC'+CAST(row_number () over (order by (Description)) as varchar(10))
            FROM T1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,''); 



SET @SQL = N'
SELECT [Generic Name], '+ @Sel+ N'
FROM T1
    pivot
    (
           MAX(Description) For Description IN ('+ @Cols + N')
        ) P';

EXECUTE( @SQL);

结果:

+--------------+--------+----------+-------+-------+
| Generic Name | DESC1  |  DESC2   | DESC3 | DESC4 |
+--------------+--------+----------+-------+-------+
| RESISTOR     | DESIGN | Material | POWER | Type  |
+--------------+--------+----------+-------+-------+

<强> Demo

答案 1 :(得分:0)

请尝试以下答案,希望它可以帮助您:

CREATE TABLE #TABLE
(
[Generic Name] varchar(15),
[Description]varchar(15)
)

INSERT INTO #TABLE

SELECT 'RESISTOR',  'POWER' UNION ALL
SELECT 'RESISTOR',  'Type' UNION ALL
SELECT 'RESISTOR',  'DESIGN' UNION ALL
SELECT 'RESISTOR',  'Material'

SELECT MAX(CASE WHEN RN=1 THEN [Generic Name] END)[Generic Name]
    ,MAX(CASE WHEN RN=1 THEN [Description] END)DESC1
    ,MAX(CASE WHEN RN=2 THEN [Description] END)DESC2
    ,MAX(CASE WHEN RN=3 THEN [Description] END)DESC3
    ,MAX(CASE WHEN RN=4 THEN [Description] END)DESC4
FROM(
    SELECT *,ROW_NUMBER() OVER(ORDER BY (SELECT NULL))RN from #TABLE
    )D

DROP TABLE #TABLE

结果:

Generic Name    DESC1   DESC2   DESC3   DESC4
RESISTOR        POWER   Type    DESIGN  Material