计算SQL Server中各列的出现次数

问题描述 投票:0回答:3

我想根据多列中值的出现来更新一列。

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列。它应该跳过空出现,仅在值存在时计数。

对于以上模式,出现次数应更新为

enter image description here

我该如何实现?

sql-server count find-occurrences
3个回答
1
投票

尝试一下:

Update Table1 set
    Occurrences = ISNUMERIC(jan) + ISNUMERIC(feb) + ISNUMERIC(mar) + ISNUMERIC(apr)

0
投票

最大程度地利用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


0
投票

您可以使用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
© www.soinside.com 2019 - 2024. All rights reserved.