SQL:如何比较来自2个不同表的计数但输出最大值

时间:2016-02-10 22:09:48

标签: sql count compare max

所以我有2个数据表,一个名为OCEAN,列为:TYPE1和COLOR1 另一个名为LAKE的列为:TYPE2和COLOR2 我试图弄清楚如何输出OCEAN表中的类型在OCEAN表中的类型比LAKE表更多。

现在我有:

    SELECT type1 from
    (SELECT type1, count(type1) as count1 from OCEAN 
    GROUP BY type1
    HAVING count1 > count2 from 
    (SELECT type2, count(type2) as count2 from LAKE GROUP BY type2)
    )

但显然不起作用。 有什么想法吗?

2 个答案:

答案 0 :(得分:0)

我认为这是一个解决方案:

select type1
from ocean 
group by type1
having count(type1) > (
    select count(type2) from lake where type2=type1 group by type2)

您可以使用this online demo

答案 1 :(得分:0)

您可以使用OUTER APPLY ..

执行此操作
SELECT  Type1,
        COUNT(*) Type1Count,
        Type2Count
FROM    Ocean o
        OUTER APPLY (SELECT COUNT(*) Type2Count
                     FROM   Lake l
                     WHERE  l.Type2 = o.Type1
                    ) oa
GROUP BY Type1,
        Type2Count
HAVING  COUNT(*) > Type2Count