在mysql中如何查询group by中两个字段当其中一个有值就加上,没有值就不加

有一种情况,比如说当某一个商品原价是100元,打折后是80元.现在需要你统计一堆商品的价格,有一些商品是没有打折的,有些是打折的,怎样用一个sql把它查出来.

已知表订单表order有2个字段分别是原价price,物资名称wares_name和折扣价zk_price.当有折扣价时就取折扣价的数值.

有2种方式:

一,select sum(case when zk_price is not null and zk_price !='' and zk_price !=0  then zk_price else price end) AS total_amount from order group by wares_name

二,,select sum(ifnull(if(zk_price=0,price,zk_price),price)) AS total_amount from order group by wares_name

两种其实都是一种方式只是不同的写法

posted @ 2025-04-14 16:37  风中的等待  阅读(27)  评论(0)    收藏  举报