你需要重寫你的查詢,子查詢和將它們連接在一起:
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;
注:我從兩個查詢中刪除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
這工作完美。謝謝。我沒有內在的聯合征服他們。 – ColorfulWind
如何將小數減少到兩個地方? (我試圖用decimal替換Float並且轉換爲cast) – ColorfulWind
只需要輸出完整結果以及分母或分子:CAST(CAST(COALESCE(na.NewAccounts,0)AS FLOAT)/ aa.AllAccounts AS DECIMAL(10,2))' – GarethD