在sql server中使用pivot或aggreate fucntion将colum转换为mutiple colum

时间:2018-03-27 10:25:10

标签: sql sql-server

我在sql表中有这样的数据

enter image description here

String

914-3000-0002
03/14/2018 13:03:10
03/16/2018 13:03:10
26074

需要转换如下(4列需要更改)

task no          start date             end date             id
914-3000-0002 | 03/14/2018 13:03:10  | 03/16/2018 13:03:10 | 26074

2 个答案:

答案 0 :(得分:1)

试试这个:

DECLARE @Tab TABLE(String VARCHAR(50))
INSERT INTO @Tab VALUES ('914-3000-0002')
INSERT INTO @Tab VALUES ('03/14/2018 13:03:10')
INSERT INTO @Tab VALUES ('03/16/2018 13:03:10')
INSERT INTO @Tab VALUES ('26074')

SELECT MAX(CASE WHEN D.RN=1 THEN D.String END)[task no]
    ,MAX(CASE WHEN D.RN=2 THEN D.String END) [start date]
    ,MAX(CASE WHEN D.RN=3 THEN D.String END) [end date]
    ,MAX(CASE WHEN D.RN=4 THEN D.String END) [id]
FROM(
    SELECT *
        ,ROW_NUMBER() OVER(ORDER BY (SELECT NULL))RN 
    FROM @Tab
    )D

<强>输出:

task no         start date          end date            id
914-3000-0002   03/14/2018 13:03:10 03/16/2018 13:03:10 26074

答案 1 :(得分:1)

为了安全地执行此操作,您需要一个指定排序的列。 SQL表表示无序集。所以:

select max(case when seqnum = 1 then string end) as taskno,
       max(case when seqnum = 2 then string end) as startdate,
       max(case when seqnum = 3 then string end) as enddate,
       max(case when seqnum = 4 then string end) as id
from (select t.*, row_number() over (order by ?) as seqnum
      from t
     ) t;

?用于订购列。如果没有排序列,您可能会尝试执行此操作并且代码似乎可以正常工作 - 但它可能会在任何时候中断。