我有这样的表
DisposalID ReportID
242 84
243 84
我希望看到它的方式
DisposalID DisposalID ReportID
242 243 84
我尝试使用数据透视表但无法实现
select
*
from
(
SELECT [DisposalID]
,[ReportID]
FROM [ClearData_Test].[dbo].[DisposalConsolidatedView] WHERE [ReportID]=84
) DataTable
PIVOT
(
Min(disposalid)
FOR reportid
IN ([84])
) PivotTable
它只给我最小或最大。任何帮助都会受到极大关注。
答案 0 :(得分:0)
由于PIVOT需要聚合,因此您当前的查询将仅返回每个DisposalId
的最小/最大值。为了获得您想要的结果,您必须创建将用作新列标题的列。
我会使用row_number()
并按ReportId
对数据进行分区。您正在使用的子查询将略微更改为以下内容:
SELECT [DisposalID]
,[ReportID]
, 'DisposalId'
+cast(row_number() over(partition by reportId
order by disposalid) as varchar(10)) seq
FROM [dbo].[DisposalConsolidatedView]
WHERE [ReportID]=84
见SQL Fiddle with Demo。这将创建一个包含值DisposalId1
和DisposalId2
的列 - 这些新值将是您的新列标题,然后您将聚合应用于现有的DisposalId
列。
最终语法为:
select DisposalId1, DisposalId2, ReportId
from
(
SELECT [DisposalID]
,[ReportID]
, 'DisposalId'
+cast(row_number() over(partition by reportId
order by disposalid) as varchar(10)) seq
FROM [dbo].[DisposalConsolidatedView]
WHERE [ReportID]=84
) DataTable
PIVOT
(
Min(disposalid)
FOR seq IN (DisposalId1, DisposalId2)
) PivotTable;
见SQL Fiddle with Demo。这将得到一个结果:
| DISPOSALID1 | DISPOSALID2 | REPORTID |
|-------------|-------------|----------|
| 242 | 243 | 84 |
答案 1 :(得分:0)
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME('DisposalID'+cast(seq as varchar(10)))
from
(
select row_number() over(partition by [reportId]
order by disposalid) seq
from [ClearData_Test].[dbo].[DisposalConsolidatedView]
) d
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT [ReportID],' + @cols + '
from
(
SELECT [ReportID], disposalid,
''disposalid''+
cast(row_number() over(partition by [reportId]
order by disposalid) as varchar(10)) seq
FROM [ClearData_Test].[dbo].[DisposalConsolidatedView]
where[ReportID]=''84''
) x
pivot
(
Min(disposalid)
for seq in (' + @cols + ')
) p '
execute sp_executesql @query;
这是我正在寻找的解决方案。