这是我的样本表:
CREATE TABLE TestSample
(
Id INT ,
StudyStartDate DATETIME ,
StudyEndDate DATETIME ,
DesignStartDate DATETIME ,
DesignEndDate DATETIME ,
StudyStartDiff INT ,
StudyEndDiff INT ,
DesignStartDiff INT ,
DesignEndDiff INT
)
INSERT INTO TestSample
VALUES (1, '2010-04-22', '2012-01-17', '2012-04-09', '2012-10-08', 635, 635, 182, 182)
INSERT INTO TestSample
VALUES (2, '2014-04-15', '2015-04-30', '2015-03-30', '2016-04-11', 380, 380, 378, 378)
SELECT *
FROM TestSample
我需要取消忽略此表,以便将StudyStartDate
和StudyStartDatediff
置于单个Milestone
代码下,并将其他列与
所以我的输出应该是这样的:
ID Mcode Mdate Variance
1 XY105 2010-04-22 635
1 XY110 2012-01-17 635
1 XY205 2012-04-09 182
1 XY210 2012-10-08 182
2 XY105 2014-04-15 380
2 XY110 2015-04-30 380
2 XY205 2015-03-30 378
2 XY210 2016-04-11 378
这背后的逻辑是
有人可以帮我解决这个问题吗?
答案 0 :(得分:0)
如果您不需要使用UNPIVOT
,这会做您需要做的事吗?
SELECT ID, 'XY105' AS Mcode, ts.StudyStartDate AS Mdate, ts.StudyStartDiff AS Variance FROM dbo.TestSample AS ts
UNION
SELECT ID, 'XY110' AS Mcode, ts.StudyEndDate AS Mdate, ts.StudyEndDiff AS Variance FROM dbo.TestSample AS ts
UNION
SELECT ID, 'XY205' AS Mcode, ts.DesignStartDate AS Mdate, ts.DesignStartDiff AS Variance FROM dbo.TestSample AS ts
UNION
SELECT ID, 'XY210' AS Mcode, ts.DesignEndDate AS Mdate, ts.DesignEndDiff AS Variance FROM dbo.TestSample AS ts
答案 1 :(得分:0)
select id,Dates1,Value1 from(
select Id,
StudyStartDate,StudyStartDiff,
StudyEndDate, StudyEndDiff,
DesignStartDate,DesignStartDiff,
DesignEndDate ,DesignEndDiff
from TestSample
) as Ts
unpivot
(Dates1 FOR Dates IN ( StudyStartDate,StudyEndDate, DesignStartDate,DesignEndDate)
) AS mrks
unpivot
(Value1 FOR Value IN ( StudyStartDiff,StudyEndDiff,DesignStartDiff,DesignEndDiff)
) AS Value
WHERE Left(Value,10) = Left(Dates,10)