如何改進下面的SQL查詢(SQL Server 2008)?我想盡量避免子查詢,和我使用的是他們夫婦產生這樣Subselect查詢改進
StateId TotalCount SFRCount OtherCount
---------------------------------------------------------
AZ 102 50 52
CA 2931 2750 181
etc...
SELECT
StateId,
COUNT(*) AS TotalCount,
(SELECT COUNT(*) AS Expr1 FROM Property AS P2
WHERE (PropertyTypeId = 1) AND (StateId = P.StateId)) AS SFRCount,
(SELECT COUNT(*) AS Expr1 FROM Property AS P3
WHERE (PropertyTypeId <> 1) AND (StateId = P.StateId)) AS OtherCount
FROM Property AS P
GROUP BY StateId
HAVING (COUNT(*) > 99)
ORDER BY StateId
你的答案應該有正確的輸出,並且根據我的經驗,'SUM(CASE ...)'與使用內部選擇相比往往是驚人的快。 – ean5533 2011-12-30 15:15:44
太棒了,謝謝!我編輯了你的答案,在「OtherCount」後刪除了一個無關的逗號。 – Scott 2011-12-30 15:24:30
+1,很好的答案 – 2011-12-30 15:40:41