0

我有这样的桌子

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

它只给我最小值或最大值。任何帮助将不胜感激。

4

2 回答 2

0

由于 PIVOT 需要聚合,因此您当前的查询将仅返回 each 的最小值/最大值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 |
于 2013-11-05T11:35:07.610 回答
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;

这就是我正在寻找的解决方案。

于 2013-11-05T15:00:00.327 回答