Sql 使用group by对同一列中的某些值进行多次计数

Sql 使用group by对同一列中的某些值进行多次计数,sql,group-by,count,Sql,Group By,Count,我有一个运行不同帐户的事件表。我们需要按帐户计算某些类型的事件 输入: | accountId | eventType | |-----------|-----------| | 1 | start | | 1 | stop | | 1 | start | | 1 | start | | 2 | start | | 2 | start | 查询: 选

我有一个运行不同帐户的事件表。我们需要按帐户计算某些类型的事件

输入:

| accountId | eventType |
|-----------|-----------|
| 1         | start     |
| 1         | stop      |
| 1         | start     |
| 1         | start     |
| 2         | start     |
| 2         | start     |
查询:

选择accountId,按accountId将(eventType='start')计数为开始,将(eventType='stop')计数为eventTable组中的停止

预期产出:

| accountId | starts    | stops     |
|-----------|-----------|-----------|
| 1         | 3         | 1         |
| 2         | 2         | 0         |
它似乎只是试图分配一个值,并对所有值进行相同的计数——这不是故意的。这将是一个围绕使用的工作

sum(eventType='start'的情况下1也为0)as开始

但是有没有更好的(更干净的)直接使用计数的方法呢

编辑:
我使用的是Athena,因此首选HIVE/Presto语法和行为。

您的查询缺少来自
子句的
,但我认为这是一个输入错误

考虑:

select 
    accountId, 
    sum(eventType = 'start') as starts, 
    sum(eventType = 'stop') as stops 
from ???
GROUP BY accountId
理由:
count()
考虑所有非
null的值。另一方面,只要|
eventType
不是
null
count()
内的条件返回布尔值或
0/1
值,具体取决于您的数据库。您需要的是对这些
0/1
值进行
sum()

请注意,上述语法仅在MySQL中受支持。如果您正在运行Postgres(这是您的原始代码将在其中运行的另一个数据库),则无需执行此操作,您可以使用
filer
子句:

select 
    accountId, 
    count(*) filter(where eventType = 'start') as starts, 
    count(*) filter(where eventType = 'stop') as stops 
from ???
GROUP BY accountId

抱歉,第一个后期编辑窗口声明支持降价。应将措辞改为“部分支持”。将重新格式化表。
count(eventType='start'然后是1 end时的情况)
?不起作用,因为它是VARCHAR值,而不是数字:
函数sum的意外参数(布尔值)。期望值:和(双精度)、和(实数)、和(整型)、和(十进制(p,s))
@DennisMeyer:你在使用哪个数据库,这是Postgres吗?雅典娜,so HIVE/Presto。重新编辑我的问题。过滤语句在雅典娜中有效!我想这也比使用case语句对数据进行转换更有效(尽管这可能与“真实”的RDBMS(如MySQL、Postgres等)更相关,因为HIVE在数据中运行)。接受您的答案,但只有在达到声誉后才会公开;-)