【发布时间】:2021-03-02 10:21:45
【问题描述】:
我的查询如下所示:
select
no, sub_no, date, id, count(distinct sub_no) as count
from
(select no, sub_no, date, id
from pre_test where type = 'B' and date = '2020-10-02'
group by no, sub_no, date, id
having min(test_activity) = max(test_activity)
and min(test_activity) = 'APPROVED'
and min(test_type) = max(test_type)
and min(test_type) = 'COMPLETED') as x
group by
no, sub_no, date, id
我对这个查询的期望是查看每个no 中有多少sub_no 有type = B,并且所有sub_no 都已被批准和完成。
我实际上得到了什么:
no sub_no date id count
--------------------------------------------
01 01-01 2020-10-02 a 1
01 01-02 2020-10-02 a 1
虽然我预计查询会返回:
no date id count
-----------------------------
01 2020-10-02 a 2
还会显示所有值为 0 的 no。
我应该如何修正我的查询?
谢谢。
【问题讨论】:
-
你使用的是什么 dbms?
-
您使用
GROUP BY no, sub_no, date, id进行子查询,然后使用GROUP BY no, sub_no, date, id将其包装在外部查询中,即完全相同的组。为什么要这么做?重点是什么?它不会改变任何东西。 --- 另外,如果您按sub_no分组,那么您为什么期望count(distinct sub_no)返回1 以外的任何值?那里没有任何意义。重新思考你在做什么。
标签: sql distinct-values