2

我有两张表如下------

表格1

CalenderType  periodNumber periodstartdate
1             1            01-01-2013
1             2            11-01-2013
1             3            15-01-2013
1             4            25-01-2013
2             1            01-01-2013
2             2            15-01-2013
2             3            20-01-2013
2             4            25-01-2013

表2

Incidents  Date
xyz        02-01-2013
xxyyzz     03-01-2013
ccvvb      12-01-2013
vvfg       16-01-2013
x3         17-01-2013
x5         24-01-2013

现在我想找出给定时间段内发生的事件数量(日历类型可能会在运行时发生变化)查询应该看起来像这样

select ....... 
from ......
where CalendarType=1

应该返回

CalendarType PeriodNumber Incidents
1            1            2
1            2            1
1            3            3
1            4            0

有人可以建议我一种方法或任何方法如何实现这一点。

注意:每个period都是可变的,size.peroid1可能有 10 天period2可能有 5 天等。

4

2 回答 2

2

我认为这可以满足您的要求,尽管我不明白您是如何得出示例输出的:

select t.CalenderType, t.periodNumber, count(*) as Incidents
from Table1 t
inner join (
  select t2.Date, t2.Incidents, max(t1.periodstartdate) as PeriodStartDate
  from Table2 t2
  inner join Table1 t1 on t2.Date >= t1.periodstartdate
  where CalenderType = 1
  group by t2.Date, t2.Incidents
) a on t.periodstartdate = a.PeriodStartDate
where CalenderType=1
group by t.CalenderType, t.periodNumber

SQL 小提琴示例

于 2013-03-12T14:16:55.857 回答
0

试试这个,一个更通用的解决方案,SQLFiddle(感谢 RedFilter 的模式):

SELECT t1.CalenderType,  t1.periodNumber, count(Incidents)
FROM Table1 t1, Table1 t11, Table2 
WHERE 
(
  (
    t1.CalenderType = t11.CalenderType 
    AND t1.periodNumber = t11.periodNumber - 1
    AND Date BETWEEN t1.periodstartdate AND t11.periodstartdate 
  ) 
  OR
  (
    t1.periodNumber = (SELECT MAX(periodNumber) FROM Table1 WHERE t1.CalenderType = CalenderType)
    AND Date > t1.periodstartdate
  )

) 
GROUP BY  t1.CalenderType,  t1.periodNumber
ORDER BY  t1.CalenderType,  t1.periodNumber
于 2013-03-12T14:16:20.337 回答