【问题标题】:SQL Server - Transpose Date from One Table To AnotherSQL Server - 将日期从一个表转置到另一个表
【发布时间】:2017-08-16 16:39:01
【问题描述】:

不知道如何将数据从一个表转置到另一个表。我使用游标吗? 样本数据:

Build Part SN DateShipped
1 123 2017-01-01
2 234 2017-02-02
3 345 2017-03-03
B 1 987 2017-01-01
B 2 876 2017-02-02
B 3 765 2017-03-03

期望的结果:

构建 Part1SN Part1Ship Part2SN Part2Ship Part3SN Part3Ship
A 123 2017-01-01 234 2017-02-02 345 2017-03-03
B 987 2017-01-01 876 2017-02-02 765 2017-03-03

【问题讨论】:

  • 如果您使用的 RDBMS 支持,您可以使用 PIVOT条件聚合 来完成。 SO中有很多例子。

标签: sql sql-server transpose


【解决方案1】:

由于您在 Pivot 中混合数据类型(日期和 int),我将给出一个动态 Pivot 的工作示例。我们在 Cross Apply 中所做的工作的日期说明。

我还假设 Part 在构建中是连续的,否则我们需要应用/嵌套 Row_Number()

示例

Declare @SQL varchar(max) = '
Select *
 From (
        Select A.Build
              ,B.*
         From  YourTable A
         Cross Apply ( values (concat(''Part'',A.Part,''SN''),  concat('''',A.SN))
                             ,(concat(''Ship'',A.Part,''Ship''),concat('''',A.DateShipped))
                     ) B (Item,Value)
      ) A
 Pivot (max([Value]) For [Item] in (' + Stuff((Select ','+QuoteName(concat('Part',Part,'SN')) 
                                                     +','+QuoteName(concat('Ship',Part,'Ship')) 
                                               From (Select Distinct Part From YourTable ) A  
                                               Order By 1 
                                               For XML Path('')),1,1,'')  + ') ) p'
Exec(@SQL)
--Print @SQL

退货

生成的 SQL 如下所示

Select *
 From (
        Select A.Build
              ,B.*
         From  YourTable A
         Cross Apply ( values (concat('Part',A.Part,'SN'),  concat('',A.SN))
                             ,(concat('Ship',A.Part,'Ship'),concat('',A.DateShipped))
                     ) B (Item,Value)
      ) A
 Pivot (max([Value]) For [Item] in ([Part1SN],[Ship1Ship],[Part2SN],[Ship2Ship],[Part3SN],[Ship3Ship]) ) p

【讨论】:

    【解决方案2】:
    select Build,
    max(case Part when 1 then SN end)   'Part1SN', max(case Part when 1 then DateShipped end) 'Part1Ship',
    max(case Part when 2 then SN end)   'Part2SN', max(case Part when 2 then DateShipped end) 'Part2Ship',
    max(case Part when 3 then SN end)   'Part3SN', max(case Part when 3 then DateShipped end) 'Part3Ship'
     from TempTable
     group by Build
    

    【讨论】:

      【解决方案3】:

      您应该尝试使用数据透视表。

      参考以下链接

      https://www.sqlshack.com/multiple-options-to-transposing-rows-into-columns/

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多