Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/74.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 即使没有结果,如何为每个组返回一行?_Sql_Oracle - Fatal编程技术网

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

Sql 即使没有结果,如何为每个组返回一行?,sql,oracle,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、订单月份、订单年份、订单半个月(该月的前半部分“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

首先,生成所有行,这可以通过交叉连接客户和时间段来完成。然后,为聚合引入信息:

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和日期部分可能有其他来源。这会将它们从订单中提取出来。

如果您知道整个数据集的每个半月、月、年的组合都会发生,那么您可以将这三件事的列表用作左连接的左侧。看起来是这样的:

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

数据库无法报告不存在的数据。数据库应该在哪里获得订单所在的年份和月份?您可以创建缺少的数据,并使用外部联接来确保包含所有日期/期间:如前面的堆栈示例所示:或@xQbert。你误解了请求。日期部分存在,只是没有分配给特定客户。
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;