7

我确定我在这里遗漏了一些东西。

我有一个这样的数据集:

FK RowNumber 值类型状态
1 1 aaaaa A 新
1 2 bbbbb B 好
1 3 ccccc A 坏
1 4 ddddd C 好
1 5 eeeee B 好
2 1 fffff C 坏
2 2 ggggg 一个新的
2 3 hhhhh C 不好
3 1 iiiiii 好
3 2 jjjjj 好

我想查询前 3 个结果并将它们作为列进行透视,因此最终结果集如下所示:

FK 值 1 类型 1 状态 1 值 2 类型 2 状态 2 值 3 类型 3 状态 3
1 aaaaa A 新 bbbbb B 好 ccccc A 坏
2 fffff C 坏 ggggg A 新 hhhhh C 坏
3 iiiiii 好 jjjjj 好

如何在 SQL Server 2005 中完成此操作?

我一直在尝试使用PIVOT进行此操作,但我仍然对该关键字非常不熟悉,并且无法让它按照我想要的方式工作。

SELECT * --Id, [1], [2], [3]
FROM
(
    SELECT Id, Value, Type, Status
    , ROW_NUMBER() OVER (PARTITION BY Id ORDER Status, Type) as [RowNumber]
    FROM MyTable
) as T
PIVOT
(
    -- I know this section doesn't work. I'm still trying to figure out PIVOT
    MAX(T.Value) FOR RowNumber IN ([1], [2], [3]),
    MAX(T.Type) FOR RowNumber IN ([1], [2], [3]),
    MAX(T.Status) FOR RowNumber IN ([1], [2], [3])
) AS PivotTable;

我的实际数据集比这个复杂一点,我需要前 10 条记录,而不是前 3 条,所以我不想简单地CASE WHEN RowNumber = X THEN...为每一条都做。

更新

我测试了下面的所有答案,发现它们中的大多数看起来都差不多,在较小的数据集(大约 3k 条记录)中没有明显的性能差异,但是在对较大的数据集运行查询时略有不同。

这是我使用 80,000 条记录并查询前 10 行中的 5 列的测试结果,所以我的最终结果集是 50 列 +Id列。我建议您自己测试它们,以确定哪一种最适合您和您的环境。

  • bluefoot对数据进行反透视和重新透视的答案平均最快,大约为 12 秒。我也喜欢这个答案,因为我发现它最容易阅读和维护。

  • Aaron 的回答koderoid 的回答都建议使用MAX(CASE WHEN RowNumber = X THEN ...), 并且在 13 秒左右的平均值之后紧随其后。

  • Rodney使用多个PIVOT语句的答案平均约为 16 秒,尽管使用较少的 PIVOT 语句可能会更快(我的测试有 5 个)。

  • 亚伦回答的前半部分建议使用 CTE 并且OUTER APPLY是最慢的。我不知道运行需要多长时间,因为我在 2 分钟后取消了它,那是大约 3k 条记录、3 行和 3 列而不是 80k 记录、10 行和 5 列。

4

5 回答 5

7

您可以尝试在三个单独的数据透视语句中进行数据透视。请试一试:

SELECT Id
    ,MAX(S1) [Status 1]
    ,MAX(T1) [Type1]
    ,MAX(V1) [Value1]
    --, Add other columns
FROM
(
    SELECT Id, Value , Type, Status
    , 'S' + CAST(ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Status, Type) AS VARCHAR(10)) [Status_RowNumber]
    , 'T' + CAST(ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Status, Type) AS VARCHAR(10)) [Type_RowNumber]
    , 'V' + CAST(ROW_NUMBER() OVER (PARTITION BY Id ORDER BY Status, Type) AS VARCHAR(10)) [Value_RowNumber]
    FROM MyTable
) as T
PIVOT
(   
    MAX(Status) FOR Status_RowNumber IN ([S1], [S2], [S3],[S4],[S5],[S6],[S7],[S8],[S9],[S10])
)AS StatusPivot
PIVOT(
    MAX(Type) FOR Type_RowNumber IN ([T1], [T2], [T3],[T4],[T5],[T6],[T7],[T8],[T9],[T10])
)AS Type_Pivot
PIVOT(
    MAX(Value) FOR Value_RowNumber IN ([V1], [V2], [V3],[V4],[V5],[V6],[V7],[V8],[V9],[V10])
)AS Value_Pivot
GROUP BY Id

我不知道选择前十名记录的标准的全部范围,但这会产生和输出可能会让你更接近你的答案。

SQL 小提琴示例

于 2012-08-31T19:32:09.657 回答
7

你可以对数据做一个UNPIVOT然后再做一个PIVOT。这可以静态或动态完成:

静态版本:

select *
from
(
  select fk, col + cast(rownumber as varchar(1)) new_col,
    val
  from 
  (
    select fk, rownumber, value, cast(type as varchar(10)) type,
      status
    from yourtable
  ) x
  unpivot
  (
    val
    for col in (value, type, status)
  ) u
) x1
pivot
(
  max(val)
  for new_col in
    ([value1], [type1], [status1], 
     [value2], [type2], [status2],
    [value3], [type3])
) p

请参阅带有演示的 SQL Fiddle

unpivot动态版本,这将在运行时获取到然后到的列列表pivot

DECLARE @colsUnpivot AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX),
    @colsPivot as  NVARCHAR(MAX)

select @colsUnpivot = stuff((select ','+quotename(C.name)
         from sys.columns as C
         where C.object_id = object_id('yourtable') and
               C.name not in ('fk', 'rownumber')
         for xml path('')), 1, 1, '')

select @colsPivot = STUFF((SELECT  ',' 
                      + quotename(c.name 
                         + cast(t.rownumber as varchar(10)))
                    from yourtable t
                     cross apply 
                      sys.columns as C
                   where C.object_id = object_id('yourtable') and
                         C.name not in ('fk', 'rownumber')
                   group by c.name, t.rownumber
                   order by t.rownumber
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')


set @query 
  = 'select *
      from
      (
        select fk, col + cast(rownumber as varchar(10)) new_col,
          val
        from 
        (
          select fk, rownumber, value, cast(type as varchar(10)) type,
            status
          from yourtable
        ) x
        unpivot
        (
          val
          for col in ('+ @colsunpivot +')
        ) u
      ) x1
      pivot
      (
        max(val)
        for new_col in
          ('+ @colspivot +')
      ) p'

exec(@query)

SQL Fiddle with Demo

两者都会产生相同的结果,但是如果您不提前知道列数,动态效果会很好。

动态版本在行号已经是数据集的一部分的假设下工作。

于 2012-08-31T19:41:31.013 回答
2

罗德尼的多支点很聪明,这是肯定的。当您进入 10X 与 3X 区域时,这里还有另外两个选择当然不那么吸引人。

;WITH a AS
(
    SELECT Id, Value, Type, Status, 
      n = ROW_NUMBER() OVER (PARTITION BY Id ORDER BY [Status], [Type])
    FROM dbo.MyTable
)
SELECT a.Id, 
 Value1 = a.Value, Type1 = a.[Type], Status1 = a.[Status],
 Value2 = b.Value, Type2 = b.[Type], Status2 = b.[Status],
 Value3 = c.Value, Type3 = c.[Type], Status3 = c.[Status]
FROM a
OUTER APPLY (SELECT * FROM a AS T2 WHERE n = a.n + 1 AND id = a.id) AS b
OUTER APPLY (SELECT * FROM a AS T2 WHERE n = b.n + 1 AND id = b.id) AS c
WHERE a.n = 1
ORDER BY a.Id;

- 或者 -

;WITH a AS
(
    SELECT Id, Value, [Type], [Status], 
      n = ROW_NUMBER() OVER (PARTITION BY Id ORDER BY [Status], [Type])
    FROM dbo.MyTable
)
SELECT Id,
  Value1  = MAX(CASE WHEN n = 1 THEN Value    END),
  Type1   = MAX(CASE WHEN n = 1 THEN [Type]   END),
  Status1 = MAX(CASE WHEN n = 1 THEN [Status] END),
  Value2  = MAX(CASE WHEN n = 2 THEN Value    END),
  Type2   = MAX(CASE WHEN n = 2 THEN [Type]   END),
  Status2 = MAX(CASE WHEN n = 2 THEN [Status] END),
  Value3  = MAX(CASE WHEN n = 3 THEN Value    END),
  Type3   = MAX(CASE WHEN n = 3 THEN [Type]   END),
  Status3 = MAX(CASE WHEN n = 3 THEN [Status] END)
FROM a
GROUP BY Id
ORDER BY a.Id;
于 2012-08-31T19:36:10.513 回答
1

这可能对您有用,尽管它并不优雅。

select aa.FK_Id
    , isnull(max(aa.Value1), '') as Value1
    , isnull(max(aa.Type1), '') as Type1
    , isnull(max(aa.Status1), '') as Status1
    , isnull(max(aa.Value2), '') as Value2
    , isnull(max(aa.Type2), '') as Type2
    , isnull(max(aa.Status2), '') as Status2
    , isnull(max(aa.Value3), '') as Value3
    , isnull(max(aa.Type3), '') as Type3
    , isnull(max(aa.Status3), '') as Status3
from
(       
    select FK_Id
            , case when RowNumber = 1 then Value else null end as Value1
            , case when RowNumber = 1 then [Type] else null end as Type1
            , case when RowNumber = 1 then [Status] else null end as Status1
            , case when RowNumber = 2 then Value else null end as Value2
            , case when RowNumber = 2 then [Type] else null end as Type2
            , case when RowNumber = 2 then [Status] else null end as Status2
            , case when RowNumber = 3 then Value else null end as Value3
            , case when RowNumber = 3 then [Type] else null end as Type3
            , case when RowNumber = 3 then [Status] else null end as Status3
    from Table1
) aa
group by aa.FK_Id
于 2012-08-31T19:44:12.963 回答
1

尝试这样的事情:

declare @rowCount int 
set @rowCount = 10

declare @isNullClause varchar(4024)
set @isnullClause = ''
declare @caseClause varchar(4024)
set @caseClause = ''

declare @i int 
set @i = 1

while(@i <= @rowCount) begin 
    set @isnullClause = @isNullClause + 
                        ' , max(aa.Value' + CAST(@i as varchar(3)) + ') as Value'    + CAST(@i as varchar(3)) +
                        ' , max(aa.Type' + CAST(@i as varchar(3)) + ') as Type'  + CAST(@i as varchar(3)) +
                        ' , max(aa.Status' + CAST(@i as varchar(3)) + ') as Status'  + CAST(@i as varchar(3)) + ' '; 
    set @caseClause = @caseClause + 
        ' , case when RowNumber = ' + CAST(@i as varchar(3)) + ' then Value else null end as Value' + CAST(@i as varchar(3)) +
        ' , case when RowNumber = ' + CAST(@i as varchar(3)) + ' then Type else null end as Type' + CAST(@i as varchar(3)) +
        ' , case when RowNumber = ' + CAST(@i as varchar(3)) + ' then Status else null end as Status' + CAST(@i as varchar(3)) + ' '


    set @i = @i + 1; 
end

declare @sql nvarchar(4000)
set @sql = 'select aa.FK_Id ' + @isnullClause + ' from ( select FK_Id ' 
            + @caseClause + '  from Table1) aa group by aa.FK_Id '

exec SP_EXECUTESQL @sql
于 2012-08-31T20:54:56.763 回答