简体   繁体   中英

sql sum column in having clause is not summing quarterly values

i would like to sum (purchase_prd) which is quarterly for customerID where purchase value is >0 and <=500. I have same customer ids in multiple purchase_prd, and would also like to see how many records show for their customerID....how do I query this? I have the following

select purchase_prd, count(*), customerID, sum(purchase_value)
from table a
where purcahse_prd between 201700 and 201712 /*data is quarterly, so 201700, 201703, 201706,201709, 201712*/
group by customerid, purchase_value
having purchase_value >0 and purchase_value<=500

my results show customerids in multiple quarters and the sums of purchase_value exceeds 500, each quarter is separate and not extracting the total of purchase_value for the entire year with the criteria of purchase_value >0 and <=500

my results are:

purchase_prd            customer ID         purchase_value
201700                          714              776
201703                           714              120
201706                           714              50
201709                            714             20
201712                           714              100

I'd like 2017 summed for customerID 714 and selected if sum of purchase_value is >0-<=500

I think you want:

select customerID, purchase_prd, count(*), sum(purchase_value)
from table a
where purchase_prd between 201700 and 201712 /*data is quarterly, so 201700, 201703, 201706,201709, 201712*/
group by customerid, purchase_prd
having sum(purchase_value) > 0 and sum(purchase_value) <= 500

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM