[英]SQL Server - Rows to Columns without Aggregation
I have data that looks like this: 我有看起来像这样的数据:
address | id
12AnyStreet | 1234
12AnyStreet | 1235
12AnyStreet | 1236
12AnyStreet | 1237
My goal is to make it look like this: 我的目标是使其看起来像这样:
Address id1 id2 id3 id4
123Any 1234 1235 1246 1237
Based on some Googling and what not, I was able to generate the following CTE: 根据一些谷歌搜索和其他方法,我能够生成以下CTE:
with cust_cte (Address, id, RID) as (
SELECT Address, id,
ROW_NUMBER() OVER (PARTITION BY (Address) ORDER BY Address) AS RID
FROM tab)
The next step would be to pivot so that for each RID, I place the associated id in the column. 下一步将是透视,以便对于每个RID,我将关联的ID放在该列中。 However, I can't seem to get the example I found to work.
但是,我似乎无法获得我发现的示例。 Rather than post the rest of the example which may not even really apply, I'll leave it up to the audience.
与其发布示例的其余部分(甚至可能并不真正适用),不如把它留给听众。 Other novel approaches not necessarily utilizing the CTE are also appreciated.
还可以理解不必利用CTE的其他新颖方法。 This will be chugging through a lot of data, so efficiency is important.
这将处理大量数据,因此效率很重要。
You can transform this data using the PIVOT
function in SQL Server. 您可以在SQL Server中使用
PIVOT
函数转换此数据。 In order to PIVOT
the data, you will want to create your new column using the row_number()
. 为了
PIVOT
数据,您将需要使用row_number()
创建新列。
If you have a known number of values, then you can hard-code the query: 如果您拥有已知数量的值,则可以对查询进行硬编码:
select *
from
(
select address, id,
'id_'+cast(row_number() over(partition by address
order by id) as varchar(20)) rn
from yourtable
) src
pivot
(
max(id)
for rn in ([id_1], [id_2], [id_3], [id_4])
) piv
See SQL Fiddle with Demo 参见带有演示的SQL Fiddle
But if the values are unknown then you will need to use dynamic SQL: 但是,如果值未知,那么您将需要使用动态SQL:
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ','
+ QUOTENAME(rn)
from
(
select 'id_'+cast(row_number() over(partition by address
order by id) as varchar(20)) rn
from yourtable
) src
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT address,' + @cols + ' from
(
select address, id,
''id_''+cast(row_number() over(partition by address
order by id) as varchar(20)) rn
from yourtable
) x
pivot
(
max(id)
for rn in (' + @cols + ')
) p '
execute(@query)
See SQL Fiddle with Demo 参见带有演示的SQL Fiddle
The result of both queries is: 这两个查询的结果是:
| ADDRESS | ID_1 | ID_2 | ID_3 | ID_4 |
-------------------------------------------
| 12AnyStreet | 1234 | 1235 | 1236 | 1237 |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.