MYSQL选择销售列出所有名称,即使它们没有出售[关闭]
Posted
技术标签:
【中文标题】MYSQL选择销售列出所有名称,即使它们没有出售[关闭]【英文标题】:MYSQL select Sales list all the names even if they are not sold [closed] 【发布时间】: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
谢谢
【问题讨论】:
先阅读w3schools.com/sql/sql_join.asp 欢迎来到 SO。请看:Why should I provide an MCRE for what seems to me to be a very simple SQL query? 并且该查询无法生成该结果。 【参考方案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
【讨论】:
以上是关于MYSQL选择销售列出所有名称,即使它们没有出售[关闭]的主要内容,如果未能解决你的问题,请参考以下文章
挑战:如何在随机或任意选择客户名称时列出与客户名称相关的所有信用卡