2014-02-28 71 views
1

我正在尋找新賬戶和所有賬戶之間的利率變化,我列出了以下兩個查詢。我需要將AllAccounts除以NewAccounts,並在同一個查詢中按城鎮分組。由於在SQL中劃分兩個查詢然後劃分爲

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 

回答

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; 

注:我從兩個查詢中刪除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 
+0

這工作完美。謝謝。我沒有內在的聯合征服他們。 – ColorfulWind

+0

如何將小數減少到兩個地方? (我試圖用decimal替換Float並且轉換爲cast) – ColorfulWind

+0

只需要輸出完整結果以及分母或分子:CAST(CAST(COALESCE(na.NewAccounts,0)AS FLOAT)/ aa.AllAccounts AS DECIMAL(10,2))' – GarethD