1

I have a table which lists the Departments and total count of incidents for each calendar month, as seen below. Data is ordered by Dept and Date fields.

What I am trying to do is to get the minimum value of the 'Count' field for the past 3 months, for each company and display it for each row in the original table.

For instance, the first record has Count=2 and there is no data prior to 2011-1-1 for Dept-001, so the min(Count) is 2. The second record has Count=9 and the min(Count) for the past 3 months is 2. and so forth...

How would you write a query to give this output? Thanks,

TABLE

Dept Count    Date
001  2        2011-1-1
001  9        2011-2-1
001  1        2011-3-1
001  4        2011-4-1
001  5        2011-5-1
001  3        2011-6-1
002  2        2011-1-1
002  7        2011-2-1
002  1        2011-3-1
002  9        2011-4-1
002  6        2011-5-1
002  1        2011-6-1

OUTPUT

Dept Min(Last 3 Month)    Date
001  2                    2011-1-1
001  2                    2011-2-1
001  1                    2011-3-1
001  1                    2011-4-1
001  1                    2011-5-1
001  3                    2011-6-1
002  2                    2011-1-1
002  2                    2011-2-1
002  1                    2011-3-1
002  1                    2011-4-1
002  1                    2011-5-1
002  1                    2011-6-1
Thracian
  • 651
  • 4
  • 8
  • 24

2 Answers2

2

You need to self-join the table with the period:

SELECT t1.dept, MIN(t2.cnt) min_last_3_month, t1.dat FROM
  tbl t1
INNER JOIN tbl t2 ON t1.dept = t2.dept
                 AND t2.dat > DATEADD(MONTH, -3, t1.dat)
                 AND t2.dat <= t1.dat
GROUP BY
  t1.dept, t1.dat
ORDER BY
  t1.dept, t1.dat

you can try it on SQLFiddle

deterministicFail
  • 1,271
  • 9
  • 28
0
SELECT  x.[Dept], x.[Date], x.[Count],
        (
            SELECT  MIN(y.[Count]) FROM dbo.MyTable y 
            WHERE   y.[Dept] = x.[Dept]
            AND     y.[Date] BETWEEN DATEADD(DAY, 1, DATEADD(MONTH, -3, x.[Date])) AND  x.[Date] -- Assumption: [Date]'s type is DATE
        ) AS MIN_Count
FROM    dbo.MyTable x;
Bogdan Sahlean
  • 19,233
  • 3
  • 42
  • 57