【发布时间】:2010-12-14 13:56:09
【问题描述】:
与我之前问过的一个问题 here 相关,我发现了一个问题,我(显然)一直在想办法。
最初的问题是如何根据可能缺少某些日表日期的月表从日表中选择最小和最大日期。基本上我需要的是包含月份日期(总是第一个)、日表中该月的最早日期和日表中该月的最晚日期的列。
所以,如果 1 月的最后一周和 2 月的第一周从日表中丢失(否则我们有 1 月和 2 月的所有日期,但没有更多),我需要:
MonthStart DayFirst DayLast
---------- ---------- ----------
2009-01-01 2009-01-01 2009-01-24
2009-02-01 2009-02-08 2009-02-28
答案是:
select
m.date as m1,
min(d.date) as m2,
max(d.date) as m3
from monthly m
join daily d
on month(d.date) = month(m.date)
and year(d.date) = year(m.date)
group by m.date
order by m.date
这适用于我给出的规格。
不幸的是,现实咬住了,月表(和日表)中有多个相同日期的记录。具体来说:
- 日期为
2007-10-16至2007-10-30(15 天)、2007-11-01至2007-11-30(30 天)和2007-12-01至2007-12-15(15 天)。 - 每个日期在两个表中都有六行(因为它们每行都有三个系统名称和两个句点。
问题是我 sum() 月度表中的一个字段,而新查询获取的值太大(与没有连接的前一个查询相比)。
聚合将查询更改为:
select
m.date as m1,
sum(m.other_field), -- added this
min(d.date) as m2,
max(d.date) as m3
from monthly m
join daily d
on month(d.date) = month(m.date)
and year(d.date) = year(m.date)
group by m.date
order by m.date
我认为由于交叉连接的进行,这些值太高了,因为每个月的数字都超出了一个常数因子,具体取决于该月日表中的天数。
我的问题是:如何在不影响该因素的情况下聚合月度表中的字段并且仍然从该月的日表中获取最小/最大日期?
【问题讨论】: