我有这张表:
tblDiving(
diving_number int primary key
diving_club int
date_of_diving date)
tblDivingClub(
number int primary key not null check (number>0),
name char(30),
country char(30))
tblWorks_for(
diver_number int
club_number int
end_working_date date)
tblCountry(
name char(30) not null primary key)
我需要写一个查询来返回一个国家的名称和其中的“超级俱乐部”的数量。 超级俱乐部是一个俱乐部,拥有超过25名工作潜水员(tblWorks_for.end_working_date为空)或去年有超过100名潜水员(tblDiving)。 在我获得国家和超级俱乐部的数量之后,我只需要展示包含超过2个超级俱乐部的国家。
我写了这两个问题:
select tblDivingClub.name,count(distinct tblWorks_for.diver_number) as number_of_guids
from tblWorks_for
inner join tblDivingClub on tblDivingClub.number = tblWorks_for.club_number,tblDiving
where tblWorks_for.end_working_date is null
group by tblDivingClub.name
select tblDivingClub.name, count(distinct tblDiving.diving_number) as number_of_divings
from tblDivingClub
inner join tblDiving on tblDivingClub.number = tblDiving.diving_club
WHERE tblDiving.date_of_diving <= DATEADD(year,-1, GETDATE())
group by tblDivingClub.name
但我不知道如何继续。 每个查询都单独工作,但我如何组合它们并从中进行选择? 这是大学任务,我不允许使用观点或临时表。
这是我的第一个程序,所以我不确定我在做什么:)
答案 0 :(得分:2)
WITH CTE AS (
select tblDivingClub.name,count(distinct tblWorks_for.diver_number) as diving_number
from tblWorks_for
inner join tblDivingClub on tblDivingClub.number = tblWorks_for.club_number,tblDiving
where tblWorks_for.end_working_date is null
group by tblDivingClub.name
UNION ALL
select tblDivingClub.name, count(distinct tblDiving.diving_number) as diving_number
from tblDivingClub
inner join tblDiving on tblDivingClub.number = tblDiving.diving_club
WHERE tblDiving.date_of_diving <= DATEADD(year,-1, GETDATE())
group by tblDivingClub.name
)
SELECT * FROM CTE
只要每个查询中的列数相同,您就可以使用UNION ALL组合查询。然后,您可以将它们滚动到公用表表达式(CTE)中并从中进行选择。