Snapshot of my data and what I want
我的数据是这样的(我附上了一张图片来显示数据和我想要的东西)
LoanNb FullNm Rule1 Rule2 Rule3 Rule4 … Rule40
100 A Fatal null null Warning null
200 A null null Fatal null null
300 B null Warning null null null
400 C null null null null null
我想要这样
LoanNb FullNm Rule Name Outcome
100 A Rule1 Critical
100 A Rule4 Warning
200 A Rule3 Critical
300 B Rule2 Warning
我在论坛中搜索过,我想我需要做一些事情,我正在尝试这个,但是没有工作。我是SQL的新手。
select *
From Tablename
Unpivot
(RuleOutcome for Rulename in ('Rule1', 'Rule2', 'Rule3', 'Rule4')
) unpiv
答案 0 :(得分:1)
declare @t table(LoanNb int, FullNm varchar(1),Rule1 varchar(10),Rule2 varchar(10), Rule3 varchar(10),Rule4 varchar(10),rule5 varchar(10))
insert into @t values
(100, 'A', 'Fatal', null, null, 'Warning', null),
(200, 'A', null, null, 'Fatal', null, null),
(300, 'B', null, 'Warning',null, null, null),
(400, 'C', null, null ,null, null, null)
SELECT loannb, fullnm, rules
FROM
(SELECT fullnm,loannb, rule1,rule2,rule3,rule4
FROM @t) p
UNPIVOT
(rules FOR setofrules IN (rule1,rule2,rule3,rule4)
)AS unpvt;
结果 loannb fullnm规则
100 A Fatal
100 A Warning
200 A Fatal
300 B Warning
(受影响的4行)