COUNT DISTINCT with CONDITIONS

前端 未结 5 651
南方客
南方客 2020-12-07 09:10

I want to count the number of distinct items in a column subject to a certain condition, for example if the table is like this:

tag | entryID
----+---------
         


        
5条回答
  •  Happy的楠姐
    2020-12-07 09:19

    This may also work:

    SELECT 
        COUNT(DISTINCT T.tag) as DistinctTag,
        COUNT(DISTINCT T2.tag) as DistinctPositiveTag
    FROM Table T
        LEFT JOIN Table T2 ON T.tag = T2.tag AND T.entryID = T2.entryID AND T2.entryID > 0
    

    You need the entryID condition in the left join rather than in a where clause in order to make sure that any items that only have a entryID of 0 get properly counted in the first DISTINCT.

提交回复
热议问题