2010-10-27 75 views
1
SELECT COUNT(sendbook.id) AS total, SUM(sendbook.num) AS num, (

SELECT COUNT(sendbook.id) 
FROM sendbook 
INNER JOIN clients ON clients.id = sendbook.clientid 
WHERE sendbook.issueid = '29' 
AND clients.area >1000 
AND clients.area <2000 
) AS area1000, (

SELECT COUNT(sendbook.id) 
FROM sendbook 
INNER JOIN clients ON clients.id = sendbook.clientid 
WHERE sendbook.issueid = '29' 
AND clients.area >2000 
AND clients.area <3000 
) AS area2000, (

SELECT COUNT(sendbook.id) 
FROM sendbook 
INNER JOIN clients ON clients.id = sendbook.clientid 
WHERE sendbook.issueid = '29' 
AND clients.area >3000 
AND clients.area <4001 
) AS area2000 
FROM `sendbook` 
WHERE sendbook.issueid = '29' 

total num area1000 area2000 area2000 
8  438  3   3  2 

您是否知道簡化查詢的方法? 思簡化查詢

+2

應該不是你的第二個 'area2000' 被命名爲 'area3000'?區域2000和3000會發生什麼情況 - 這些在您的查詢中沒有考慮到,這是正確的嗎?一些更一般的信息會很好。 – oezi 2010-10-27 08:52:00

回答

0

你需要使用case語句是這樣的:

SELECT COUNT(sendbook.id), 
(CASE 
WHEN clients.area between '1000' and '2000' THEN 1 
WHEN clients.area between '2000' and '3000' THEN 2 
WHEN clients.area between '3000' and '4000' THEN 3 
END) AS myrange FROM mytable 
GROUP BY myrange 
+0

你的情況是4行,但我的情況是1行 – love 2010-10-27 09:27:26

+0

是的但是很簡單的查詢,你只需要運行一個小循環 – 2010-10-27 09:43:39

+0

呃...謝謝! – love 2010-10-28 02:05:58