在SQL中划分两个查询然后分组

时间:2014-02-28 14:49:23

标签: sql group-by

我正在寻找新帐户和所有帐户之间的费率变化,我在下面列出了两个查询。我需要通过AllAccounts划分NewAccounts,在同一个查询中获取该百分比并按城镇分组。感谢

SELECT DISTINCT  Count(NewAccounts), Town
FROM   (SELECT Stuff)
WHERE   (Newaccounts)
Group By Town
;
SELECT DISTINCT  Count(AllAccounts), Town
FROM   (SELECT DifferentSTUFF)
WHERE   (AllAccounts)
Group By Town

1 个答案:

答案 0 :(得分:3)

您需要将查询重写为子查询并将它们连接在一起:

SELECT  CAST(na.NewAccounts AS FLOAT) / aa.AllAccounts
FROM    (   SELECT Count(NewAccounts) AS NewAccounts, Town
            FROM   (SELECT Stuff)
            WHERE   (Newaccounts)
            GROUP BY Town
        ) na
        INNER JOIN
        (   SELECT Count(AllAccounts) AS AllAccounts, Town
            FROM   (SELECT DifferentSTUFF)
            WHERE   (AllAccounts)
            GROUP BY Town
        ) aa
            ON aa.Town = na.Town;

n.b。我已从两个查询中删除DISTINCT,因为它是多余的。在NewAccounts上浮动的强制转换是为了避免将结果整数除法隐式转换回整数。

根据每个查询中数据的可用性,您可能需要稍微改变一下,例如,如果您不会总是在城镇的新帐户中有结果,那么最好将其写为:

SELECT  CAST(COALESCE(na.NewAccounts, 0) AS FLOAT) / aa.AllAccounts
FROM    
        (   SELECT Count(AllAccounts) AS AllAccounts, Town
            FROM   (SELECT DifferentSTUFF)
            WHERE   (AllAccounts)
            GROUP BY Town
        ) aa
        LEFT JOIN
        (   SELECT Count(NewAccounts) AS NewAccounts, Town
            FROM   (SELECT Stuff)
            WHERE   (Newaccounts)
            GROUP BY Town
        ) na
            ON aa.Town = na.Town