取消隐藏2列

时间:2016-01-26 18:17:23

标签: sql-server-2008

这是我的样本表:

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

我需要取消忽略此表,以便将StudyStartDateStudyStartDatediff置于单个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

这背后的逻辑是

  • 对于MCode XY105:Mdate应该是StudyStartDate&差异:StudyStartDiff
  • 对于MCode XY110:Mdate应该是StudyEndDate&差异:StudyEndDiff
  • 对于MCode XY205:Mdate应该是DesignStartDate&差异:DesignStartDiff
  • 对于MCode XY110:Mdate应该是DesignEndDate&差异:DesignEndDiff **

有人可以帮我解决这个问题吗?

2 个答案:

答案 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)