客户订单总数按月计算,即使客户在一个月内没有订单,也会列出所有客户,在一个SQL语句中?

时间:2015-07-23 17:57:27

标签: sql ansi-sql

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

使用合并功能是可以接受的。

按月列出客户订单总数:

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');

生成此表:

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

2 个答案:

答案 0 :(得分:1)

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

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

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

答案 1 :(得分:0)

制作客户和月份的笛卡尔产品是鸡蛋中的第一个裂缝......然后左边加入/合并结果。

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
             );