让我们说我有一个带有类ID的表“ trips”,这是另一个表“ classes”的外键,还有一个列“ trip”,它只是文本。
62 'Zoo'
62 'Park'
62 'Observatory'
64 'Park'
64 'Zoo'
81 'Park'
我想算一下没有上天文台的班级数。 我怎么知道的?
答案 0 :(得分:2)
一种方法是聚合:
select class
from trips t
group by class
having sum(case when trip = 'Observatory' then 1 else 0 end) = 0;
如果有一个类表(您可能这样做),请使用not exists
:
select c.*
from classes c
where not exists (select 1
from trips t
where t.classid = c.classid and
t.trip = 'Observatory'
);
答案 1 :(得分:0)
计算班级数量,计算去天文台的班级数量,然后减去:
WITH cteTotal_class_count AS (SELECT COUNT(*) AS TOTAL_CLASS_COUNT
FROM CLASSES),
cteObservatory_class_count AS (SELECT COUNT(DISTINCT CLASS_ID) AS OBSERVATORY_CLASS_COUNT
FROM TRIPS
WHERE UPPER(TRIP) = 'OBSERVATORY')
SELECT TOTAL_CLASS_COUNT - OBSERVATORY_CLASS_COUNT AS COUNT_OF_CLASSES_WHO_DIDNT_GO
FROM cteTotal_class_count
CROSS JOIN cteObservatory_class_count
答案 2 :(得分:0)
与上一个答案的想法相同,但有所简化:
SELECT (SELECT count(distinct class_id) FROM trips) -
(SELECT count(distinct class_id) FROM trips WHERE trip = 'Observatory');