COUNT DISTINCT with CONDITIONS

前端 未结 5 640
南方客
南方客 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条回答
  • 2020-12-07 09:18

    This may work:

    SELECT Count(tag) AS 'Tag Count'
    FROM Table
    GROUP BY tag
    

    and

    SELECT Count(tag) AS 'Negative Tag Count'
    FROM Table
    WHERE entryID > 0
    GROUP BY tag
    
    0 讨论(0)
  • 2020-12-07 09:18

    Code counts the unique/distinct combination of Tag & Entry ID when [Entry Id]>0

    select count(distinct(concat(tag,entryId)))
    from customers
    where id>0
    

    In the output it will display the count of unique values Hope this helps

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 09:25

    You can try this:

    select
      count(distinct tag) as tag_count,
      count(distinct (case when entryId > 0 then tag end)) as positive_tag_count
    from
      your_table_name;
    

    The first count(distinct...) is easy. The second one, looks somewhat complex, is actually the same as the first one, except that you use case...when clause. In the case...when clause, you filter only positive values. Zeros or negative values would be evaluated as null and won't be included in count.

    One thing to note here is that this can be done by reading the table once. When it seems that you have to read the same table twice or more, it can actually be done by reading once, in most of the time. As a result, it will finish the task a lot faster with less I/O.

    0 讨论(0)
  • 2020-12-07 09:25

    Try the following statement:

    select  distinct A.[Tag],
         count(A.[Tag]) as TAG_COUNT,
         (SELECT count(*) FROM [TagTbl] AS B WHERE A.[Tag]=B.[Tag] AND B.[ID]>0)
         from [TagTbl] AS A GROUP BY A.[Tag]
    

    The first field will be the tag the second will be the whole count the third will be the positive ones count.

    0 讨论(0)
提交回复
热议问题