【问题标题】:SQL count occurrences without counting duplicates in another columnSQL 计算出现次数而不计算另一列中的重复项
【发布时间】:2022-01-07 07:16:02
【问题描述】:

我有一张桌子:

Date       | ID | Company | Click 
-----------+----+---------+--------
01/01/2021 | 01 | Us      | 1
01/01/2021 | 01 | Us      | 1
01/01/2021 | 01 | Other   | 1
01/01/2021 | 02 | Us      | 0 
01/01/2021 | 02 | Other   | 0
02/01/2021 | 03 | Us      | 1 
02/01/2021 | 03 | Us      | 1 
02/01/2021 | 04 | Us      | 0

我想按日期分组并计数:每天有多少不同的 ID,有多少 唯一 ID 有 clicked=1Company="Us"

我当前的代码是:

create table grouped as 
select date
, count(distinct ID) as ID_count
, sum(case when company="Us" and clicked=1 then 1 else 0 end) as Click_count
from have 
group by 1

结果应该是这样的:

Date       | ID_count | Click_count
-----------+----------+------------
01/01/2021 | 2        | 1
02/01/2021 | 2        | 1

您会注意到我的代码计算了重复的 ID,因此 click_count 列在两个日期中都取值 2。我该如何解决?

【问题讨论】:

  • 实际上,您的查询返回 Click_count = 1: sqlfiddle.com/#!15/ef22e8/10(在 PostgreSQL 上执行)。请不要使用group by 1。请改用group by date
  • 请标记您的数据库

标签: sql proc-sql


【解决方案1】:

您应该使用COUNT() 来计算具有CASE 表达式的不同IDs:

COUNT(DISTINCT CASE WHEN company = 'Us' AND clicked = 1 THEN ID END) AS click_count 

【讨论】:

    【解决方案2】:

    使用filter条件聚合的PostgreSQL解决方案:

    select date, 
           count(distinct id) id_count,
           count(distinct id) filter (where click = 1 and company = 'Us') click_count 
    from the_table
    group by date;
    

    如果您的数据库缺少条件聚合 filter 功能,则可以使用标量子查询(@forpas 建议的替代方案)。

    select date, 
           count(distinct id) id_count,
           (
             select count(distinct id) 
             from the_table
             where click = 1 and company = 'Us' and date = t.date
           ) click_count 
    from the_table t
    group by date;
    

    SQL Fiddle

    【讨论】:

      猜你喜欢
      • 2019-03-27
      • 2018-07-07
      • 1970-01-01
      • 2021-03-10
      • 1970-01-01
      • 2021-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多