SQL,将数据合并为一行

时间:2014-12-23 11:22:17

标签: sql sql-server

我有以下查询来获取特定的Area

Select 
    Id, Name 
from 
    Area 
Where 
    (Id = 1)

每个Area可以在AreaFiles表中有2个文件,因此我将查询更改为:

SELECT     
    Area.Id, Area.Name, AreaFiles.FileName
FROM
    AreaFiles 
INNER JOIN
    Area ON AreaFiles.AreaId = Area.Id
WHERE
    (Area.Id = 1) 

结果是:

Id | Name | FileName
--- ------ ----------
1    abc     file1.jpg
1    abc     file2.jpg

我想将这些行合并为一行以获取此信息:

Id | Name | FileName1 | FileName2
--- ------ ------------------------
1    abc     file1.jpg   file1.jpg

有可能吗?

2 个答案:

答案 0 :(得分:4)

要实现此目的,您需要使用PIVOT

请点击此处查看示例 - http://www.codeproject.com/Tips/500811/Simple-Way-To-Use-Pivot-In-SQL-Query

因此,对于您的示例,这将是

SELECT ID,NAME, [1] AS FILENAME1, [2] AS FILENAME2 FROM
(SELECT ID, FILENAME, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY ID) AS ROWNUM) FROM AREA A
PIVOT ((MAX(ID) FOR ROWNUM IN [1],[2])) AS PVT

答案 1 :(得分:-1)

为此您需要使用条款

with first as (select id,name,filename from area),
     second as (select id,name,filename from area)

SELECT first.id,first.name,first.filename,second.filename
FROM first,second
where first.id=second.id;