SQL - 如何将多个记录作为一个没有数据透视的记录插入?

时间:2013-01-31 09:06:56

标签: sql-server

我想从多个记录创建一个查询作为一条记录,但我不想使用Pivot,有没有解决方案?

这是表格:

ID   Element_Name  Value
1    Parmitha      100
2    Anggun        200
3    Chandra       300
4    BagusofTerror 400

我希望结果是这样的:

paramitha , anggun, chandra , bagusofterror
100 , 200, 300, 400

3 个答案:

答案 0 :(得分:1)

您可以使用for xml path ('')来转置列的值。

例如,你可以写

select Element_Name + ', '
from TheTable
for xml path ('');

获取Parmitha, Anggun, Chandra, BagusofTerror,

这是一个现场演示:http://www.sqlfiddle.com/#!3/71f88/24

答案 1 :(得分:0)

试试这个: -

Select 
    MAX(CASE WHEN colID = 1 THEN value ELSE NULL END) AS [Parmitha],
    MAX(CASE WHEN colID = 2 THEN value ELSE NULL END) AS [Anggun],
    MAX(CASE WHEN colID = 3 THEN value ELSE NULL END) AS [Chandra],
    MAX(CASE WHEN colID = 4 THEN value ELSE NULL END) AS [BagusofTerror]

FROM    
(
    SELECT  ROW_NUMBER() OVER (ORDER BY ID) AS colID,
            ID,
            Element_Name,
            value
        FROM    Sample
    ) AS d

SQL DEMO

考虑到Wolf的答案,使用动态查询和xml路径

DECLARE @cols AS NVARCHAR(MAX),
@query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' 
                    + convert(varchar(max), Element_Name, 120)
                from Sample
        FOR XML PATH(''), TYPE
        ).value('.', 'varchar(MAX)') 
    ,1,1,'')


set @query = 'SELECT' + @cols + ' from 
         (
            select  value, Element_Name
            from Sample
        ) x
        pivot 
        (
            max(value)
            for Element_Name in (' + @cols + ')
        ) p '

 execute(@query);

Demo

顺便说一下你不使用PIVOT。使用PIVOT可以达到相同的效果

 Select [Parmitha],[Anggun],[Chandra],[BagusofTerror] 
 FROM 
 (
  Select value,element_name from Sample
 )src
 pivot
 (
  max(value)
  for Element_Name in ([Parmitha],[Anggun],[Chandra],[BagusofTerror])
 )pvt

答案 2 :(得分:0)

您还可以使用COALESCE将结果列转换为varchar变量:

CREATE TABLE #Pivot
(ID int, Element_Name varchar(50), Value int)

INSERT #Pivot values (1,'Parmitha',100)
INSERT #Pivot values (2,'Anggun',200)
INSERT #Pivot values (3,'Chandra',300)
INSERT #Pivot values (4,'BagusofTerror',400)

DECLARE @titles VARCHAR(1000)
DECLARE @values VARCHAR(1000)
SET @titles = ''
SET @values = ''

SELECT @titles = @titles + COALESCE(Element_Name + ',' , '')
FROM #Pivot ORDER BY ID

SELECT @values = @values + COALESCE(convert(varchar, Value) + ',' , '')
FROM #Pivot ORDER BY ID

SELECT @titles
UNION ALL
SELECT @values

给出:

Parmitha,安谷,钱德拉,BagusofTerror,

100200300400,