开发者

How do I count how many of these columns have a value in SQL?

Assume the following table:

ID | Item1 | Item2 | Item3 | Item4 | Item5
------------------------------------------
A  | NULL  | NULL  | YES   | YES   | NULL
B  | NULL  | NULL  | NULL  | YES   | NULL
C  | NULL  | NULL  | NULL  | NULL  | NULL

I wa开发者_如何学JAVAnt to return the following data set:

ID  | Count
------------
A   | 2
B   | 1
C   | 0

Basically, I want a count how many of the columns of Item1-5 are NOT NULL for that ID

How can I do this in MS-SQL?


Not tested, but something like this should work.

SELECT
  Id,
  SUM(
    CASE WHEN Item1 is NULL THEN 0 ELSE 1 END
    +
    CASE WHEN Item2 is NULL THEN 0 ELSE 1 END
    +
    CASE WHEN Item3 is NULL THEN 0 ELSE 1 END
    +
    CASE WHEN Item4 is NULL THEN 0 ELSE 1 END
    +
    CASE WHEN Item5 is NULL THEN 0 ELSE 1 END
    ) 'Count'
FROM 
   tableName
GROUP BY 
   Id


Try:

DECLARE @YourTable table (ID char(1), Item1 varchar(3), Item2 varchar(3), Item3 varchar(3), Item4 varchar(3), Item5 varchar(3))
INSERT @YourTable VALUES ('A'  , NULL  , NULL  , 'YES' , 'YES' , NULL)
INSERT @YourTable VALUES ('B'  , NULL  , NULL  , NULL  , 'YES' , NULL)
INSERT @YourTable VALUES ('C'  , NULL  , NULL  , NULL  , NULL  , NULL)

SELECT
    ID, CASE WHEN ITEM1 IS NULL THEN 0 ELSE 1 END
       +CASE WHEN ITEM2 IS NULL THEN 0 ELSE 1 END
       +CASE WHEN ITEM3 IS NULL THEN 0 ELSE 1 END
       +CASE WHEN ITEM4 IS NULL THEN 0 ELSE 1 END
       +CASE WHEN ITEM5 IS NULL THEN 0 ELSE 1 END AS [Count]
    FROM @YourTable

OUTPUT:

ID   Count
---- -----------
A    2
B    1
C    0

(3 row(s) affected)


This should do it:

SELECT ID, (case when item1 is null then 0 else 1 end)+
           (case when item2 is null then 0 else 1 end)+
           (case when item3 is null then 0 else 1 end)+
           (case when item4 is null then 0 else 1 end)+
           (case when item5 is null then 0 else 1 end) AS Count 
FROM Table
ORDER BY ID

I hope this is a hypothetical question and not an actual production table.


Just another option: If you're in sql 2k5 or later you can also use an unpivot to count all non-null values. You won't get any rows for zero-counts directly from this query though. It does however save the tedium of case statements.

select
    ID, count(ItemCount) as ItemCount
from
(
    select ID, Item1, Item2, Item3, Item4, Item5
    from TableA a
) t
unpivot
(
    ItemCount for Item in
    (
        Item1, Item2, Item3, Item4, Item5
    )
) as unpvt
group by
    ID


Another technique.

SELECT
    ID, 
    (SELECT COUNT(C) FROM( 
            SELECT Item1 C 
            UNION ALL 
            SELECT Item2 
            UNION ALL 
            SELECT Item3 
            UNION ALL 
            SELECT Item4 
            UNION ALL 
            SELECT Item5)
             D)
AS [Count]
FROM @YourTable
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜