简体   繁体   中英

Divide two queries in SQL then group by

I am looking for the rate change between new accounts and all accounts, I have both queries listed below. I need to divide NewAccounts by AllAccounts, take that percentage and group by town in the same query. Thanks

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

You need to rewrite your queries as subqueries and join them together:

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;

nb I have removed DISTINCT from both queries as it is redundant. The cast to float on NewAccounts is to avoid the implicit conversion of the result integer division back to an integer.

You may need to alter this slightly depending on the availability of data in each of the queries, ie if you won't always have a result in the new accounts for a town it would be better written as:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM