2017-08-05 98 views
1

我的數據庫的快照MySQL查詢範圍

enter image description here

我想pcl_No目前的數量在規定範圍內獲得數(SUM(tv_land + tv_imp)

我已經寫了查詢,但我越來越無效使用組錯誤的

select 
count(CASE WHEN sum(tv_land+tv_imp) BETWEEN 0 AND 10000 THEN 1 END) as count0_10000 
    from 
tax_l2006 
where red_date = 0 
GROUP BY pcl_no 

樣本輸出 0-10000 10000-20000 30000-40000 >40000 2 3 1 8

+0

您的數據表明'pcl_no'是唯一的。有沒有每個重複? –

+0

'pcl_no'在數據庫中是唯一的 –

回答

2

我覺得你只是想:

select sum((tv_land + tv_imp) between 0 and 10000) as count0_10000 
from tax_l2006 
where red_date = 0; 

MySQL的對待真正的布爾爲 「1」 的數字背景和「:

select count(CASE WHEN tv_land + tv_imp BETWEEN 0 AND 10000 THEN 1 END) as count0_10000 
from tax_l2006 
where red_date = 0; 

,我會在MySQL更簡單地寫0「爲false,所以總結布爾值計算它的真實次數。

對於其餘列,您可以遵循相同的模式。

如果pcl_no不是唯一的,你需要的值相加,那麼你可以使用子查詢:

select sum(total between 0 and 10000) as count0_10000 
from (select pcl_no, sum(tv_land + tv_imp) as total 
     from tax_l2006 
     where red_date = 0 
     group by pcl_no 
    ) p; 

然而,數據表明列是唯一的,所以額外的聚集不必要。

+0

它的工作!謝謝 –