从两个表的并集中选择最高值

时间:2014-08-19 21:28:23

标签: sql sql-server union

试图从联盟中选出前5个国家,但它似乎没有起作用。 这是我的代码:

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

    UNION 

    SELECT country_number, country_name, COUNT(DISTINCT number)
    FROM
    (
        SELECT tc.country_number, tc.country_name, tdc.number, count(*) as diveCount
        FROM tblCountry tc
        INNER JOIN tblDivingClub AS tdc   ON tdc.country = tc.country_number
        INNER JOIN tblDiving  AS tdv    ON tdv.diving_club = tdc.number
        WHERE tdv.date_of_diving >= DATEADD(year,-1, GETDATE())
        GROUP BY tc.country_number, tc.country_name, tdc.number
        HAVING count(*) > 6
    ) as der2
    GROUP BY country_number, country_name
)as combinedTable

它不会接受“combinedTable”或我在“as”之后放置的任何其他名称/命令。

3 个答案:

答案 0 :(得分:1)

在第一次查询联合时,您需要一个聚合计数的别名。所有列必须在union的第一个查询中具有名称。由于您使用函数计算值,因此必须使用别名为其指定名称:

SELECT country_number, country_name, COUNT(DISTINCT number) as countNumber

你不喜欢SQL的结构让它表明代码的问题是在代码文件的完整另一端吗? :)

答案 1 :(得分:1)

您可以尝试为

指定列名
COUNT(DISTINCT number)

甚至从两个选项中删除此列。

答案 2 :(得分:0)

您可以简化查询,未经测试:

SELECT TOP 5 country_number, country_name
FROM
(
    SELECT tc.country_number, tc.country_name, tdc.number, count(*) as tot_cnt
    FROM tblCountry tc
    JOIN tblDivingClub AS tdc   ON tdc.country = tc.country_number
    JOIN tblWorks_for  AS tw    ON tw.club_number = tdc.number
    JOIN tblDiver      AS td    ON td.diver_number = tw.diver_number
    WHERE tw.end_working_date IS NULL
       OR tdv.date_of_diving >= DATEADD(year,-1, GETDATE())
    GROUP BY tc.country_number, tc.country_name, tdc.number
    HAVING count(*) > CASE WHEN tw.end_working_date IS NULL THEN 1 ELSE 6 END
) as T