group by - How to combine WHERE and HAVING in a MySQL query -
how write query mysql filter out total pay less zero. have tried different commands using 'having' can't figure out proper syntax.
this command:
select tickets.idno, tickets.pay, tickets.material tickets ( tickets.pay <> 0 or tickets.material <> 0 ) , tickets.district = 'ho' , tickets.datepaid null order tickets.name
with result set:
ho0045 -140 0 ho2203 -45 0 ho2411 -5 0 ho2411 20 0 ho3448 -156 0 ho2519 2000 0 ho0075 -300 0 ho1669 -55 0 ho2666 -200 0 ho2666 -200 0 ho3447 -400 0 ho3447 400 0
this result now, needs eliminate records total pay + total material rows given idno less zero. example; rows ho2411 , ho2519 should appear not rest.
having
meant filter out whole groups, that, need reduce query group by
. unfortunately can't reverse grouping operation after filtering groups.
so have subquery filter groups, join
result table find rows corresponding idno:
select t.idno, t.pay, t.material tickets t inner join ( select idno, sum(pay) pay, sum(material) material tickets group idno having pay + material < 0 ) total using (idno) t.district = 'ho' , t.datepaid null order t.name;
Comments
Post a Comment