31

我有一个包含 4 列的表,在第 5 列中,我想存储前 4 列中有多少非空列的计数。例如:

其中 X 是任意值:

Column1 | Column2 | Column3 | Column4 | Count
  X     |    X    |   NULL  |    X    |   3
 NULL   |   NULL  |    X    |    X    |   2
 NULL   |   NULL  |   NULL  |   NULL  |   0
4

4 回答 4

43
select
    T.Column1,
    T.Column2,
    T.Column3,
    T.Column4,
    (
        select count(*)
        from (values (T.Column1), (T.Column2), (T.Column3), (T.Column4)) as v(col)
        where v.col is not null
    ) as Column5
from Table1 as T
于 2013-08-12T18:09:26.613 回答
21
SELECT   Column1,
         Column2,
         Column3,
         Column4,
         CASE WHEN Column1 IS NOT NULL THEN 1 ELSE 0 END + 
         CASE WHEN Column2 IS NOT NULL THEN 1 ELSE 0 END + 
         CASE WHEN Column3 IS NOT NULL THEN 1 ELSE 0 END + 
         CASE WHEN Column4 IS NOT NULL THEN 1 ELSE 0 END AS Column5
FROM     Table
于 2013-08-12T17:49:22.327 回答
4
SELECT Column1, Column2, Column3, Column4,
  Column5 = LEN(COALESCE(LEFT(Column1,1),'')) 
          + LEN(COALESCE(LEFT(Column2,1),''))
          + LEN(COALESCE(LEFT(Column3,1),'')) 
          + LEN(COALESCE(LEFT(Column4,1),''))
 FROM dbo.YourTable;

演示:

DECLARE @x TABLE(a VARCHAR(32),b INT,c VARCHAR(32),d VARCHAR(32));

INSERT @x VALUES
('01',3023,NULL,'blat'),
('02',NULL, NULL,'blat'),
('03',5,NULL,'blat'),
('04',24,'bo','blat'),
(NULL, NULL, NULL, NULL);

SELECT a, b, c, d,
    LEN(COALESCE(LEFT(a,1),'')) 
  + LEN(COALESCE(LEFT(b,1),''))
  + LEN(COALESCE(LEFT(c,1),'')) 
  + LEN(COALESCE(LEFT(d,1),''))
 FROM @x;
于 2013-08-12T17:58:12.170 回答
0

这将要求您在每次更新任何其余列时对该列运行UPDATE查询,或者如果您的数据库允许您设置触发器,则您可以设置触发器。Count

如果您要创建这样的视图,那么以下查询就可以了,

SELECT
  Column1,
  Column2,
  Column3,
  Column4,
  (
    COALESCE((CASE WHEN Column1 IS NOT NULL THEN 1 ELSE 0 END), 0)
    + COALESCE((CASE WHEN Column2 IS NOT NULL THEN 1 ELSE 0 END), 0)
    + COALESCE((CASE WHEN Column3 IS NOT NULL THEN 1 ELSE 0 END), 0)
    + COALESCE((CASE WHEN Column4 IS NOT NULL THEN 1 ELSE 0 END), 0)
  ) AS Count
FROM some_table;
于 2021-10-01T06:38:02.763 回答