2013-04-10 68 views
1

我需要從不同表中檢索具有不同條件的多個列。 什麼,我有如下SQL查詢:檢索具有不同條件的列

SELECT 
(SELECT COUNT(*) FROM Table1 WHERE Price >= 0 Price < 10) AS 'Group1', 
(SELECT COUNT(*) FROM Table1 WHERE Price >= 10 AND Price < 20) AS 'Group2', 
(SELECT COUNT(*) FROM Table1 WHERE Price >= 20 AND Price < 30) AS 'Group3', 
(SELECT COUNT(*) FROM Table2 WHERE Price >= 0 Price < 10) AS 'Group4', 
(SELECT COUNT(*) FROM Table2 WHERE Price >= 10 AND Price < 20) AS 'Group5', 
(SELECT COUNT(*) FROM Table2 WHERE Price >= 20 AND Price < 30) AS 'Group6' 

只是想知道有沒有什麼更好的方式來重組爲上述條件更好的查詢?

回答

4

有,

SELECT SUM(CASE WHEN Price >= 0 Price < 10 THEN 1 END) AS 'Group1', 
     SUM(CASE WHEN Price >= 10 AND Price < 20 THEN 1 END) AS 'Group2', 
     SUM(CASE WHEN Price >= 20 AND Price < 30 THEN 1 END) AS 'Group3', 
     SUM(CASE WHEN Price >= 0 Price < 10 THEN 1 END) AS 'Group4', 
     SUM(CASE WHEN Price >= 10 AND Price < 20 THEN 1 END) AS 'Group5', 
     SUM(CASE WHEN Price >= 20 AND Price < 30 THEN 1 END) AS 'Group6' 
FROM table2 
+0

爲什麼好,有什麼區別?問題中還有2個表格。 – Alex 2013-04-10 06:10:23

+0

@Alexey它只會傳遞一次表格,而不是調用6'SELECT'語句 – 2013-04-10 06:12:30

+0

@J W但由於價格限制,它不會執行全面掃描。所以在一起看起來都一樣。 – Alex 2013-04-10 06:14:17

2

用j W.加起來table1的上述精彩查詢

SELECT SUM(CASE WHEN T1.Price >= 0 Price < 10 THEN 1 END) AS 'Group1', 
     SUM(CASE WHEN T1.Price >= 10 AND Price < 20 THEN 1 END) AS 'Group2', 
     SUM(CASE WHEN T1.Price >= 20 AND Price < 30 THEN 1 END) AS 'Group3', 
     SUM(CASE WHEN T2.Price >= 0 Price < 10 THEN 1 END) AS 'Group4', 
     SUM(CASE WHEN T2.Price >= 10 AND Price < 20 THEN 1 END) AS 'Group5', 
     SUM(CASE WHEN T2.Price >= 20 AND Price < 30 THEN 1 END) AS 'Group6' 
FROM table1 T1, table2 T2 
+0

太棒了。謝謝。 – My2ndLovE 2013-04-10 07:25:36

+0

快樂...... – user2135380 2013-04-10 07:33:14