我在解开某些数据时遇到了麻烦。我在这里看到其他的例子来解开表格,但我有一些需要不透明的对。我的数据集中实际上有10多个疾病/日期对,但我选择了三对来简化示例。
这是我的源数据:
MRN GUMCID Event BreastID BreastDate ColonID ColonDate PancID PancDate
2000012 90000001 event_1 42 1/1/2000 43 8/5/2014 44 8/6/2012
2008006 90000020 event_1 102 5/7/2003 103 9/11/2012
2000012 90002002 event_1 900 8/5/2004 902 12/5/2009
2000012 90002002 event_2 1000 9/6/2006
以下是我需要将其转换为:
MRN GUMCID Event TissueType Date ID
2000012 90000001 event_1 BreastID 1/1/2000 42
2000012 90000001 event_1 ColonID 8/5/2014 43
2000012 90000001 event_1 PancID 8/6/2012 44
2008006 90000020 event_1 BreastID 5/7/2003 102
2008006 90000020 event_1 ColonID 9/11/2012 103
2000012 90002002 event_1 BreastID 8/5/2004 900
2000012 90002002 event_1 PancID 12/5/2009 902
2000012 90002002 event_2 BreastID 9/6/2006 1000
我已经无意识地摸索并交叉申请,似乎无法使这项工作。任何想法都表示赞赏!
答案 0 :(得分:2)
DECLARE @TABLE TABLE
(MRN INT, GUMCID INT, [Event] VARCHAR(10), BreastID INT,
BreastDate DATE, ColonID INT, ColonDate DATE, PancID INT, PancDate DATE)
INSERT INTO @TABLE VALUES
(2000012, 90000001,'event_1', 42 ,'1/1/2000', 43 ,'8/5/2014' , 44 ,'8/6/2012'),
(2008006, 90000020,'event_1', 102 ,'5/7/2003', 103 ,'9/11/2012', NULL, NULL),
(2000012, 90002002,'event_1', 900 ,'8/5/2004', 902 ,'12/5/2009', NULL, NULL),
(2000012, 90002002,'event_2', 1000 ,'9/6/2006', NULL, NULL , NULL, NULL)
SELECT MRN
,GUMCID
,[Event]
,TissueType
,CONVERT(VARCHAR(10),
CASE
WHEN TissueType = 'BreastID' THEN BreastDate
WHEN TissueType = 'ColonID' THEN ColonDate
WHEN TissueType = 'PancID' THEN PancDate
END, 103) AS [Date]
,ID
FROM @Table t
UNPIVOT (ID FOR TissueType IN (BreastID, ColonID, PancID)
)up
╔═════════╦══════════╦═════════╦════════════╦════════════╦══════╗
║ MRN ║ GUMCID ║ Event ║ TissueType ║ Date ║ ID ║
╠═════════╬══════════╬═════════╬════════════╬════════════╬══════╣
║ 2000012 ║ 90000001 ║ event_1 ║ BreastID ║ 01/01/2000 ║ 42 ║
║ 2000012 ║ 90000001 ║ event_1 ║ ColonID ║ 05/08/2014 ║ 43 ║
║ 2000012 ║ 90000001 ║ event_1 ║ PancID ║ 06/08/2012 ║ 44 ║
║ 2008006 ║ 90000020 ║ event_1 ║ BreastID ║ 07/05/2003 ║ 102 ║
║ 2008006 ║ 90000020 ║ event_1 ║ ColonID ║ 11/09/2012 ║ 103 ║
║ 2000012 ║ 90002002 ║ event_1 ║ BreastID ║ 05/08/2004 ║ 900 ║
║ 2000012 ║ 90002002 ║ event_1 ║ ColonID ║ 05/12/2009 ║ 902 ║
║ 2000012 ║ 90002002 ║ event_2 ║ BreastID ║ 06/09/2006 ║ 1000 ║
╚═════════╩══════════╩═════════╩════════════╩════════════╩══════╝
答案 1 :(得分:1)
select mrd, gumcid, event, tissuetype, date, id
from tbl
cross apply (
values
('breastid', breastid, breastdate),
('colonid', colonid, colondate),
('pancid', pancid, pancdate)
) t(tissuetype, id, date)
where id is not null