mySQL 关于如何向列中添加更多信息的问题

mySQL question on how to add more info to a column

得到这个 table 包含关于客户、日期和他们的购买价值的信息。 假设他们中的一些人在 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

您可以在子查询中枚举客户,然后将 12 月的记录与 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

这会为每个客户提供一行,他们在 2000 年 12 月的总 spent - 或者 0 如果他们在那个月没有消费。

在现实生活中,您通常会有一个单独的 table 来存储客户,您将使用它来代替子查询。