【问题标题】:MYSQL select Sales list all the names even if they are not sold [closed]MYSQL选择销售列出所有名称,即使它们没有出售[关闭]
【发布时间】:2021-03-23 00:55:04
【问题描述】:

我需要选择商品的销售和金额。

我会使用脚本

select it.name
     , sum(sa.cash) 
  from items it 
  join sale sa 
    on it.id = sa.iditems
 where sa.time = '2020-11-10' 
 order 
    by it.nazev

这将列出我,例如

name   cash
Book   300
Mug    400

但是那天我有更多的商品不出售,我还需要列出它们,以便将 0 或 null 写为总和

结果应该是

Name   cash
Book   300
Mug    400
Soap    0
Cover   0
Sheet   0

谢谢

【问题讨论】:

标签: mysql sql sum left-join aggregate-functions


【解决方案1】:

这是一个left join 和聚合:

select it.name, coalesce(sum(sa.cash) , 0) as cash
from items it 
left join sale sa on it.id = sa.iditems and sa.time = '2020-11-10' 
group by it.name
order by it.name

您也可以使用子查询来做到这一点:

select it.name,
    (select coalesce(sum(sa.cash) , 0) from sale sa where sa.iditems = it.id and sa.time = '2020-11-10') as cash
from items it
order by it.name

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-06
    • 1970-01-01
    • 1970-01-01
    • 2020-10-31
    • 2015-11-13
    • 1970-01-01
    相关资源
    最近更新 更多