mysql问题

z18hc3ub  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(175)

得到了这个包含客户,日期和他们的购买价值信息的表。假设他们中的一些人在11月买了一些东西,但在12月什么也没买。现在,我试着让所有的客户+所有他们花费的,并使用ifnull()对那些在12月没有购买任何东西的客户。我正在为12月过滤它,我得到的只是那些在12月购买了东西的客户,是的。。。我知道,但我肯定有办法,但我就是想不出来。任何帮助都是受欢迎的。干杯

Customers    Date           Spent
John1        2000-11-01     12
John2        2000-11-02     33
John3        2000-11-03     13
John4        2000-11-04     24
John5        2000-11-05     36
John6        2000-12-01     55
John7        2000-12-02     16
John8        2000-12-04     33
John9        2000-12-03     18
John10       2000-12-03     13
gz5pxeao

gz5pxeao1#

您可以在子查询中枚举客户,然后使用 left join :

select c.customers, coalesce(sum(t.spent), 0) total_spent
from (select distinct customers from mytable) c
left join mytable t 
    on  t.customers = c.customers
    and t.date >= '2000-12-01'
    and t.date <  '2001-01-01'
group by c.customers

这将为每个客户提供一行,以及他们的 spent 2000年12月——或 0 如果他们在那一个月里没有消费。
在实际情况中,通常会有一个单独的表来存储客户,而不是使用子查询。

相关问题