我想根据多列中值的出现来更新一列。
SQL Server 2017架构设置:
CREATE TABLE Table1 (Part varchar(10),Jan int,Feb int,Mar int,Apr int,Occurrences int)
INSERT INTO Table1 (Part,Jan,Feb,Mar,Apr,Occurrences)VALUES('AAA',null,2,null,1,null),
('BBB',2,3,5,7,null),
('CCC',3,null,null,null,null),
('DDD',4,7,1,null,null)
我想基于Jan,Feb,Mar,Apr列中存在的值来更新Occurrences列。它应该跳过空出现,仅在值存在时计数。
对于以上模式,出现次数应更新为
我该如何实现?
尝试一下:
Update Table1 set
Occurrences = ISNUMERIC(jan) + ISNUMERIC(feb) + ISNUMERIC(mar) + ISNUMERIC(apr)
最大程度地利用iif()
功能。
update table1 set Occurrences = iif(coalesce(Jan, 0) != 0, 1, 0)
+ iif(coalesce(Feb, 0) != 0, 1, 0)
+ iif(coalesce(Mar, 0) != 0, 1, 0)
+ iif(coalesce(Apr, 0) != 0, 1, 0);
请参见dbfiddle。
您可以使用unpivot
来做到这一点,但除此之外,您还需要传递所拥有的列数(查询中的4 - ...
:]
SELECT Part, 4 - COUNT(*) FROM (
SELECT *
FROM @Table1
UNPIVOT (MonthVal FOR [Month] IN (Jan, Feb, Mar, Apr)) AS unpvt
) a GROUP BY Part