Count of non-null columns in each row

后端 未结 3 1433
一向
一向 2020-12-05 07:22

I have a table that contains 4 columns and in the 5th column I want to store the count of how many non-null columns there are out of the previous 4. For example:

Whe

3条回答
  •  时光取名叫无心
    2020-12-05 07:45

    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;
    

    Demo:

    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;
    

提交回复
热议问题