SQL将多行合并为一行

时间:2017-05-30 15:57:15

标签: sql-server

我正在尝试使用相同ID的行并将它们返回到同一行。我的数据如下所示:

ID  Fruit
1   Banana
1   Apple
1   Grapefruit
2   Cherry
2   Blueberry
3   Lime
3   Pear

我希望它看起来像这样:

ID  Fruit   Fruit1  Fruit2
1   Banana  Apple   Grapefruit
2   Cherry  Blueberry   NULL

我已经尝试过这个查询,但我似乎没有太多运气:

SELECT a.[ID],a.[Fruit],b.[Fruit]
FROM [test].[dbo].[Fruit] a
JOIN [test].[dbo].[Fruit] b
ON a.ID = b.ID
WHERE a.FRUIT <> b.FRUIT

有人可以帮忙吗?

谢谢!

3 个答案:

答案 0 :(得分:1)

如果未修复水果计数,您可以使用动态脚本:

IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t
CREATE TABLE #t(ID INT,Fruit VARCHAR(100))
INSERT INTO #t(ID,Fruit)
SELECT 1,'Banana' UNION
SELECT 1,'Apple' UNION
SELECT 1,'Grapefruit' UNION
SELECT 2,'Cherry' UNION
SELECT 2,'Blueberry' UNION
SELECT 3,'Lime' UNION
SELECT 3,'Pear'
DECLARE @sql NVARCHAR(max),@cols VARCHAR(max)
SELECT @cols=ISNULL(@cols+',','')+t.col FROM (
   SELECT *,'Fruit'+LTRIM(ROW_NUMBER()OVER(PARTITION BY ID ORDER BY(SELECT 1) )) AS col FROM #t AS t
) AS t GROUP BY t.col




SET @sql='
SELECT * FROM (
   SELECT *,''Fruit''+LTRIM(ROW_NUMBER()OVER(PARTITION BY ID ORDER BY(SELECT 1) )) AS col FROM #t AS t
) AS t  PIVOT(MAX(Fruit) FOR col in ('+@cols+')) p
'
PRINT @sql
EXEC(@sql)
IF OBJECT_ID('tempdb..#t') IS NOT NULL DROP TABLE #t
ID          Fruit1     Fruit2     Fruit3
----------- ---------- ---------- ----------
1           Apple      Banana     Grapefruit
2           Blueberry  Cherry     NULL
3           Lime       Pear       NULL

答案 1 :(得分:0)

您可以结合使用row_number这样的窗口函数,然后使用带有CASE的{​​{1}}表达式进行一些条件聚合,以获得所需的结果:

MAX()

查看Demoselect Id, Fruit = max(case when rn = 1 then Fruit end), Fruit1 = max(case when rn = 2 then Fruit end), Fruit2 = max(case when rn = 3 then Fruit end) from ( select Id, Fruit, rn = row_number() over(partition by Id order by Id) from [test].[dbo].[Fruit] ) d group by Id; 函数为每个row_number()创建一个唯一的数字,然后使用此数字以及idCASE,您将数据行转换为列。

答案 2 :(得分:0)

您可以使用pivot执行此操作,如下所示:

Select Id, [0] as Fruit, [1] as [Fruit1], [2] as [Fruit2] from (
    Select *, RowN = Row_Number() over (partition by Id order by Fruit) - 1 from yourtable )
pivot ( max(Fruit) for RowN in ([0], [1],[2]) ) p