即使没有结果,如何为每个组返回一行?

时间:2015-11-20 21:05:30

标签: sql oracle

我正在使用包含客户订单的数据库。这些订单包含客户ID,订单月份,订单年份,订单半月(上半年' FH'或上半年' LH'当月)和订购数量。

我想查询给定月份的每位客户的每月总计。这是我到目前为止所拥有的。

SELECT id, half_month, month, year, SUM(nbr_ord)
FROM Orders
WHERE month = 7
      AND year = 2015
GROUP BY id, half_month, year, month

这样做的问题是,如果客户在半个月内没有订购任何东西,那么这段时间内就不会有一行返回。

我希望每半个月为每个客户排一行。如果他们在半个月内没有订购任何东西,那么应该返回一行,其中包括他们的ID,月份,年份,半月份以及订购号码的0。

3 个答案:

答案 0 :(得分:0)

首先,生成所有行,您可以使用cross join客户和时间段。然后,引入聚合信息:

select i.id, t.half_month, t.month, t.year, coalesce(sum(nbr_ord), 0)
from (select distinct id from orders) i cross join
     (select distinct half_month, month, year
      from orders
      where month = 7 and year = 2015
     ) t left join
     orders o
     on o.id = i.id and o.half_month = t.half_month and
        o.month = t.month and o.year = t.year
group by i.id, t.half_month, t.month, t.year;

注意:您可能拥有id和日期部分的其他来源。这会将它们从orders拉出来。

答案 1 :(得分:0)

如果您知道整个数据集中每个半月,月,年组合的出现,您可以使用这三个事物的列表作为左连接的左侧。这看起来像这样:

Select t1.half_month, t1.month, t1.year, t2.ID, t2.nbr_ord from
(Select half_month, month, year)t1
Left Join
    (SELECT id, half_month, month, year, SUM(nbr_ord)nbr_ord
    FROM Orders
        WHERE month = 7
        AND year = 2015
    GROUP BY id, half_month, year, month)t2
on  t1.half_month = t2.half_month
and t1.month = t2.month
and t1.year = t2.year

答案 2 :(得分:0)

SELECT m.id, m.half_month, m.year, t.nbr_order
FROM (
    SELECT Id, sum(nbr_order) AS nbr_order
    FROM Orders
    GROUP BY id
    ) t
INNER JOIN Orders m
    ON t.Id = m.id
WHERE m.month = 7
    AND m.year = 2015;