postgresql sql count distinct by col and sum false and true

ki1q1bka  于 2023-04-05  发布在  PostgreSQL
关注(0)|答案(2)|浏览(103)

如何使用Sqlstatement查询Expect Count结果

ID      StuId    IsDone    ExpectCount
11111   q-01     false        1         
11111   q-02     false        2      
11111   q-03     false        3        
11111   q-02     true         2   
11111   q-04     false        3   
22222   q-04     false        2
11111   q-01     true         1  
11111   q-01     true         1

expect if same ID StuId IsDone = true将忽略它。

11111 = 3
22222 = 1

但得到了

11111 = 1
22222 = 1

我的查询

SELECT ID, count(*)
FROM
(SELECT DISTINCT StuId, ID, IsDone FROM Student s where IsDone = false) stu
group by ID;
qv7cva1a

qv7cva1a1#

您可以通过更改查询as in this demo来获得预期的输出。

SELECT ID, COUNT(DISTINCT StuId) - SUM(CASE WHEN IsDone = true THEN 1 ELSE 0 END) as ExpectedCount
FROM Student
GROUP BY ID;

输出:
| 身份证|ExpectedCount|
| --------------|--------------|
| 小行星1111|三|
| 小行星2222|1|

b1uwtaje

b1uwtaje2#

这里的正确解决方案是进行2级聚合。首先,我们可以通过IDStuId进行聚合,以确定哪些StuId只有错误的IsDone值。然后我们单独通过ID进行聚合,以获得纯错误计数。

WITH cte AS (
    SELECT ID, StuId, COUNT(*) FILTER (WHERE IsDone = true) cnt
    FROM Student
    GROUP BY ID, StuId
)

SELECT ID, COUNT(*) FILTER (WHERE cnt = 0) AS cnt
FROM cte
GROUP BY ID
ORDER BY ID;

相关问题