【问题标题】:Count occurrences across columns in SQL Server计算 SQL Server 中各列的出现次数
【发布时间】:2019-12-05 06:55:45
【问题描述】:

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

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

对于上述架构,出现列应更新为

我怎样才能做到这一点?

【问题讨论】:

    标签: sql-server count find-occurrences


    【解决方案1】:

    试试这个:

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

    【讨论】:

    • @红魔。如何使查询动态化,以便月份名称 jan、feb、mar 等。更新语句中没有指定?你能帮忙吗?
    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      您可以使用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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-07
        • 1970-01-01
        • 1970-01-01
        • 2011-01-11
        • 1970-01-01
        • 2017-09-29
        • 1970-01-01
        相关资源
        最近更新 更多