我有商品价格表sh,id ,price(价格) ,date(日期),name(名字)这些字段
,我原来的sql是要查询:select price,date,name from sh where data='2019-05-09' and sum(price) !=0
目的就是查询这天总和不为0的所有商品价格,这样写不让写,说这里不能用分组函数,请问要怎么写呢?
我具体业务是对账表,里面也就几个字段,进账跟出账是同一个字段,进账用正数,出账用负数,如果当天进账跟出账和不为0 ,那就是账不平,需要展示所有账目信息。跟这个差不多。
按照你的意思 应该是查询 这天 所有price合计不为0 的商品。可以利用分组统计函数实现,具体如下:
select price,date,name from sh where date='2019-05-09' and name in (select name from sh where date='2019-05-09' group by name having sum(price) <>0)
有的数据库,不等于用的不是 !=,而是 <>
select price,date,name from sh where data='2019-05-09' having sum(price) <>0
这样写,因为聚合函数不能做为查询条件,如果非要做为查询条件,得放在having里面
select a.price,a.date1,a.name from sh a,
(select sum(price) as sumprice,date1 from sh where date1='2019-05-09' group by date1) b
where a.date1=b.date1 and b.sumprice<>0