mysql按X分组并显示Total1(当Field = 0同一个表时)和Total2(当Field = 1时)

时间:2018-02-22 19:56:33

标签: mysql

我有这个查询返回图像显示:

SELECT a.idarticle, c.stock, a.libelle as 'Libelle', sum(a.price * o.quantity) as `Total` from command c
inner join store s on c.idstore = s.idstore
inner join operation o on c.idcommand = o.idcommand
inner join article a on o.idarticle = a.idarticle
group by o.idarticle, c.stock

Image

我想要:ID,Libelle,Total1(当股票= 0时),Total2(当股票= 1时)

谢谢

2 个答案:

答案 0 :(得分:2)

我认为这就是你要找的东西:

SELECT a.idarticle, a.libelle as 'Libelle', 
sum(case when stock = 0 then a.price * o.quantity) as `Total1` ,
sum(case when stock = 1 then a.price * o.quantity) as `Total2` 
from command c
inner join store s on c.idstore = s.idstore
inner join operation o on c.idcommand = o.idcommand
inner join article a on o.idarticle = a.idarticle
group by a.idarticle, a.libelle 

答案 1 :(得分:1)

试试这个:

  SELECT a.idarticle, a.libelle as `Libelle`, 
        sum(if(a.stock=0,a.price * o.quantity, 0)) `Total0`,
        sum(if(a.stock=1,a.price * o.quantity, 0)) `Total1`,
      --sum(a.price * o.quantity) as `Total` 
  from command c
  inner join store s on c.idstore = s.idstore
  inner join operation o on c.idcommand = o.idcommand
  inner join article a on o.idarticle = a.idarticle
  group by a.idarticle, a.stock;