我在sql表中有这样的数据
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
答案 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;
?
用于订购列。如果没有排序列,您可能会尝试执行此操作并且代码似乎可以正常工作 - 但它可能会在任何时候中断。