我有一个月度表(仅包含一个月的第一天的行,并且具有唯一性约束,所以每个月只有一个),还有一个日表,每天的信息相似(同一笔交易,每天仅一个):
Monthly table Daily table ------------- ----------- 2009-01-01 2009-01-01 2009-02-01 2009-01-02 : : : : 2009-09-01 2009-01-31 2009-02-01 : : 2009-02-28 2009-03-01 : : 2009-09-01
但可能会缺少几天。
我想运行一个查询,该查询针对月表中的每个日期返回该日期以及日表中该月的最小和最大日期(如果绝对必要,请使用标准SQL,最好是DB2专用的标准SQL)。
因此,如果缺少一月的最后一周和二月的第一周,我需要:
MonthStart FirstDay LastDay ---------- ---------- ---------- 2009-01-01 2009-01-01 2009-01-24 2009-02-01 2009-02-08 2009-02-28 : : 2009-09-01 2009-09-01 2009-01-30
这是我的查询:
select m.date as m1, dx.d1 as m2, dx.d2 as m3 from monthly m, ( select min(d.date) as d1, max(d.date) as d2 from daily d where month(d.date) = month(m.date) and year(d.date) = year(m.date) ) as dx;
但我得到了错误:
DSNT408I SQLCODE = -206, ERROR: M.DATE IS NOT A COLUMN OF AN INSERTED TABLE, UPDATED TABLE, OR ANY TABLE IDENTIFIED IN A FROM CLAUSE, OR IS NOT A COLUMN OF THE TRIGGERING TABLE OF A TRIGGER DSNT418I SQLSTATE = 42703 SQLSTATE RETURN CODE
DSNT408I SQLCODE = -206, ERROR: M.DATE IS NOT A COLUMN OF
AN INSERTED TABLE, UPDATED TABLE, OR ANY TABLE IDENTIFIED
IN A FROM CLAUSE, OR IS NOT A COLUMN OF THE TRIGGERING
TABLE OF A TRIGGER
DSNT418I SQLSTATE = 42703 SQLSTATE RETURN CODE
有人对如何最好地做到这一点有任何建议吗?
SELECT m.date as m1, MIN(d.date) as m2, MAX(d.date) as m3 -- COUNT(d.date) as NbOfDays -- if so desired... FROM monthly m JOIN daily d ON month(d.date) = month(m.date) and year(d.date) = year(m.date) WHERE -- some condition GROUP BY m.date ORDER BY m.date -- or something else...
请注意,这种类型的查询(与问题和到目前为止的其他查询一样,相对较慢,因为它们暗示着要进行表扫描,因此可以为每个[qualify]计算出month(x)和year(x)行(即在WHERE子句中放置日期范围当然会有所帮助)。如果这种查询类型经常运行,并且表的大小很大, 则为这些计算值添加一列可能会很有用 (或可能是组合值(“年-月”),因此不仅不必进行计算,而且可以为基础列建立索引。