根据可变期间分组日期

时间:2013-03-12 13:57:55

标签: mysql sql

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

表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天等。

2 个答案:

答案 0 :(得分: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 Fiddle Example

答案 1 :(得分:0)

试试这个,更通用的解决方案SQLFiddle(感谢RedFilter for schema):

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