2011-01-23 145 views
3

如何使此SQL查詢更高效?使SQL查詢更高效

SELECT 
    (SELECT COUNT(*) FROM table WHERE price < 10) AS priceUnder10, 
    (SELECT COUNT(*) FROM table WHERE price BETWEEN 10 AND 20) AS price10to20, 
    (SELECT COUNT(*) FROM table WHERE price > 20) AS priceOver20, 
    (SELECT COUNT(*) FROM table WHERE colour = 'Red') AS colourRed, 
    (SELECT COUNT(*) FROM table WHERE colour = 'Green') AS colourGreen, 
    (SELECT COUNT(*) FROM table WHERE colour = 'Blue') AS colourBlue; 

我已經對pricecolour列的索引,所以我要尋找一個更好的方式來彙總數據。

我已經看過使用GROUP BY,HAVING,自連接和窗口函數,但不能解決如何達到相同的結果。

任何建議非常感謝。

回答

8
SELECT 
     COUNT(CASE WHEN price < 10 THEN 1 END) AS priceUnder10, 
     COUNT(CASE WHEN price BETWEEN 10 AND 20 THEN 1 END) AS price10to20, 
     COUNT(CASE WHEN price> 20 THEN 1 END) AS priceOver20, 
     COUNT(CASE WHEN colour = 'Red' THEN 1 END) AS colourRed, 
     COUNT(CASE WHEN colour = 'Green' THEN 1 END) AS colourGreen, 
     COUNT(CASE WHEN colour = 'Blue' THEN 1 END) AS colourBlue 
from YourTable 
WHERE price IS NOT NULL OR colour IN ('Red','Green','Blue') 
+1

感謝,偉大的答案,但爲什麼是'WHERE'必要嗎? – gjb

+2

@gjb - 這可能不是,但想象你有一個1,000,000行表,只有1行在''Red','Green','Blue'中有非空價格或顏色。其他999,999行將不會不同的結果,但仍然沒有它被掃描。當然,你可能知道你的數據沒有這個分佈('價格'可能不可以爲空),它也可能被刪除! –

2

根據您的數據庫如何處理布爾表達式,這一點:

select sum(price<10),sum(price between 10 and 20)... from tab; 

或本

select sum(case when price<10 then 1 else 0 end),sum(case when price between 10 and 20 then 1 else 0 end)... from tab; 

可能的幫助。

0
SELECT count(*) as products, 

if(price < 10, 'price band 1', 
if (price between 10 and 20, 'price band 2', 
    'price band 3' 
) 
) as priceband, 
    t.colour 

from table t 
group by t.colour, pricebrand 

這會給你

products colour priceband 
53   red  price band 1 
65   red  price band 2 
12   blue  price band 1 
23   blue  price band 2 

+0

這嵌套結果,這不是我正在尋找的。仍然有用,知道,謝謝。 – gjb