如何在where子句中使用多个计数来比较sql中table的数据?
How to use multiple counts in where clause to compare data of a table in sql?
我想将 table 的数据与其其他记录进行比较。具有特定条件的行数必须与没有 where 子句但在同一分组中的行数相匹配。
下面是table
-------------
id name time status
1 John 10 C
2 Alex 10 R
3 Dan 10 C
4 Tim 11 C
5 Tom 11 C
输出应该是 time = 11,因为在 status = 'C'
上添加 where 子句时,时间列分组的计数不同
SELECT q1.time
FROM (SELECT time,
Count(id)
FROM table
GROUP BY time) AS q1
INNER JOIN (SELECT time,
Count(id)
FROM table
WHERE status = 'C'
GROUP BY time) AS q2
ON q1.time = q2.time
WHERE q1.count = q2.count
这给出了所需的输出,但是否有更好、更有效的方法来获得所需的结果?
你在找这个吗:
select t.*
from table t
where not exists (select 1 from table t1 where t1.time = t.time and t1.status <> 'C');
但是你可以这样做:
select time
from table t
group by time
having sum (case when status <> 'c' then 1 else 0 end ) = 0;
如果你想要所有行都满足where
子句的次数,那么在Postgres中,你可以这样表示:
select time
from t
group by time
having count(*) = count(*) filter (where status = 'C');
我想将 table 的数据与其其他记录进行比较。具有特定条件的行数必须与没有 where 子句但在同一分组中的行数相匹配。
下面是table
-------------
id name time status
1 John 10 C
2 Alex 10 R
3 Dan 10 C
4 Tim 11 C
5 Tom 11 C
输出应该是 time = 11,因为在 status = 'C'
上添加 where 子句时,时间列分组的计数不同SELECT q1.time
FROM (SELECT time,
Count(id)
FROM table
GROUP BY time) AS q1
INNER JOIN (SELECT time,
Count(id)
FROM table
WHERE status = 'C'
GROUP BY time) AS q2
ON q1.time = q2.time
WHERE q1.count = q2.count
这给出了所需的输出,但是否有更好、更有效的方法来获得所需的结果?
你在找这个吗:
select t.*
from table t
where not exists (select 1 from table t1 where t1.time = t.time and t1.status <> 'C');
但是你可以这样做:
select time
from table t
group by time
having sum (case when status <> 'c' then 1 else 0 end ) = 0;
如果你想要所有行都满足where
子句的次数,那么在Postgres中,你可以这样表示:
select time
from t
group by time
having count(*) = count(*) filter (where status = 'C');