在一份 SQL 报表中按月列出客户订单总数,列出/所有客户,即使客户在一个月内没有订单?

Customer order total by month, w/ all customers listed, even if customer had no orders in a month, in one SQL statement?

按月获取所有客户订单总数的列表,如果客户在给定月份没有订单,则包括该月的一行,订单总数为 0。在一份声明中?总计已计算,不需要聚合函数。

合并函数的使用是acceptable.

给定按月列出的客户订单总数:

create table orders (cust char(1), month num, exps num);
insert into orders
    values('a', 1, 5)
    values('b', 2, 4)
    values('c', 1, 8);

以及客户名单:

create table custs(cust char(1));
insert into custs
    values('a')
    values('b')
    values('c')
    values('d');

生成这个 table:

cust, month, exps
 a, 1, 5
 a, 2, 0
 b, 1, 0
 b, 2, 4
 c, 1, 8
 c, 2, 0
 d, 1, 0
 d, 2, 0

制作客户和月份的笛卡尔积是鸡蛋的第一个裂缝......然后左 join/coalesce w/结果。

select all_possible_months.cust,
       all_possible_months.month,
       coalesce(orders.exps,0) as exps
from
       (select order_months.month,
          custs.cust
       from
          (select distinct month
           from
             orders
           ) as order_months,
          custs
        ) all_possible_months
left join
        orders on(
             all_possible_months.cust = orders.cust and
             all_possible_months.month = orders.month
             );
select or1.cust, a.[month], sum(coalesce(or2.[exps], 0)) as exps
from (
    select 1 as[month] union all select 2
) a cross join (select distinct cust from custs) or1
left join orders or2 on or2.[month] = a.[month] and or2.cust = or1.cust
group by or1.cust, a.[month]
order by or1.cust,a.[month]

Sqlfiddle

另一个版本从 table 中获取所有现有月份。我们的测试数据的结果相同:

select or1.cust, a.[month], sum(coalesce(or2.[exps], 0)) as exps
from (
    select distinct [month] from orders
) a cross join (select distinct cust from custs) or1
left join orders or2 on or2.[month] = a.[month] and or2.cust = or1.cust
group by or1.cust, a.[month]
order by or1.cust,a.[month]

Sqlfiddle