sql db2从任一表中选择记录

时间:2012-04-06 18:26:05

标签: sql join db2

我有一个订单文件,包含订单ID和发货日期。订单只能在星期一 - 星期五发货。这意味着周六和周日没有选择记录。

我使用相同的订单文件来获取所有订单日期,日期格式相同(yyyymmdd)。

我想根据订单日期从订单文件中选择所有记录的计数...并且(我相信)完全外部联接(或者可能正确加入?)日期文件...因为我想要见

20120330 293

20120331 0

20120401 0

20120402 920

20120403 430

20120404 827

等...

但是,我的sql语句仍未返回第31个和第1个的零记录。

with DatesTable as (
   select ohordt "Date" from kivalib.orhdrpf
   where ohordt between 20120315 and 20120406
   group by ohordt order by ohordt
)

SELECT ohscdt, count(OHTXN#) "Count"

FROM KIVALIB.ORHDRPF full outer join DatesTable dts on dts."Date" = ohordt
--/*order status = filled & order type = 1 & date between (some fill date range)*/

WHERE OHSTAT = 'F' AND OHTYP = 1 and ohscdt between 20120401 and 20120406

GROUP BY ohscdt ORDER BY ohscdt

任何想法我做错了什么?

谢谢!

1 个答案:

答案 0 :(得分:0)

这是因为当时没有数据,它们不会显示为行。您可以使用递归CTE在查询可以连接的两个值之间构建一个连续的日期列表:

它看起来像:

WITH dates (val) AS (
    SELECT CAST('2012-04-01' AS DATE)
    FROM SYSIBM.SYSDUMMY1
        UNION ALL
    SELECT Val + 1 DAYS
    FROM dates
    WHERE Val < CAST('2012-04-06' AS DATE)
)

SELECT d.val AS "Date", o.ohscdt, COALESCE(COUNT(o.ohtxn#), 0) AS "Count"
FROM dates AS d
LEFT JOIN KIVALIB.ORDHRPF AS o
  ON o.ohordt = TO_CHAR(d.val, 'YYYYMMDD')
WHERE o.ohstat = 'F'
  AND o.ohtyp = 1