具有2个条件的SQL查询

时间:2014-08-19 17:01:03

标签: sql sql-server

我有这些表格:

  1. tblCountry - country_number,country_name
  2. tblDivingClub - club_number,country_number(FK)
  3. tblDiver - diver_number,diver_name,startWorkingDate,endrtWorkingDate。
  4. tblWorks_for -diver_number(FK),club_number(FK)
  5. 我需要编写一个没有视图或临时表的查询,这些查询会显示一些国家/地区:country_number,country_name,以及该国有25名或更多潜水员的潜水俱乐部数量(结束工作日期为IS NULL)。

    这就是我到目前为止写的代码:

    SELECT country_number, country_name,
    (   SELECT count(distinct tblDivingClub.number) 
        FROM tblDivingClub 
        inner join tblCountry on tblDivingClub.country = tblCountry.country_number
         WHERE (
            (  SELECT count(tblWorks_for.diver_number) 
               FROM tblWorks_for 
               INNER JOIN tblDivingClub on  tblWorks_for.club_number = tblDivingClub.number 
               WHERE tblWorks_for.end_working_date IS null
                    and tblDivingClub.number =   tblWorks_for.club_number) >25)
    ) as number_of_clubs
    FROM tblCountry 
    INNER JOIN tblDivingClub on tblCountry.country_number = tblDivingClub.country 
    WHERE tblCountry.country_number = tblDivingClub.country 
    GROUP by country_number, country_name
    

2 个答案:

答案 0 :(得分:1)

尝试这样的事情:

SELECT country_number, country_name, COUNT(DISTINCT club_number)
FROM
(
    SELECT tc.country_number, tc.country_name, tdc.club_number, count(*) as tot_cnt
    FROM tblCountry tc
    INNER JOIN tblDivingClub AS tdc   ON tdc.country_number = tc.country_number
    INNER JOIN tblWorks_for  AS tw    ON tw.club_number = tdc.club_number
    INNER JOIN tblDiver      AS td    ON td.diver_number = tw.diver_number
    WHERE endrtWorkingDate IS NULL
    GROUP BY tc.country_number, tc.country_name, tdc.club_number
    HAVING count(*) >= 25
) as der
GROUP BY country_number, country_name;

答案 1 :(得分:1)

SQL预测聚合条件的需要是一件好事 - 如果你怀疑必须有一个更简单的方法,那你就是对的。我想你想要的东西:

SELECT country_number, country_name, count(distinct tblDivingClub.number) 
FROM tblCountry 
INNER JOIN tblDivingClub on tblCountry.country_number = tblDivingClub.country 
WHERE tblCountry.country_number = tblDivingClub.country 
GROUP by country_number, country_name
HAVING count(case when tblWorks_for.end_working_date IS null then 1 else null end) > 25