Frage

I'm sure there must be a neat solution but I can't seem to get anything to work in the way that I require. Im sure you should be able to acheive this using a recursive CTE. Im trying to steer clear of creating lots of Tmp Tables.

Main table (or recursive Anchor?) aggregates the data by Person , Month & Year and applies a count & ranking to the result

SELECT  
  PersonID
, Mth
, Yr
, COUNT(*) as DLY_Cnt
, RANK () OVER (PARTITION BY PersonID, Mth ORDER BY Yr DESC) as YrRnk
FROM #BkgSummary
GROUP BY PersonID, Mth, Yr

Example result

PersonID    Mth     Yr  DLY_Cnt    Dep_YrRnk
6000995     6      2010    2           1
6000995     6      2009    1           2
6000995     6      2007    1           3
6000995     8      2011    2           1

I need to the aggregate the result further (and add it to the previous resultset) to give me essentially a count of Bookings made in the same month in previous years (plus its own value) on PersonID & Mth

So something like: SUM(DLY_Cnt) as DPY_Cnt by PersonID & Mth WHERE YrRnk >= Anchor YrRnk

Example result I'm after:

PersonID    Mth     Yr  DLY_Cnt    Dep_YrRnk    DPY_Cnt
6000995     6      2010    2           1            4
6000995     6      2009    1           2            2
6000995     6      2007    1           3            1
6000995     8      2011    2           1            2
War es hilfreich?

Lösung

If I understand the results correctly, you want a cumulative sum of DLY_Cnt. You can do this quite readily in SQL Server 2012:

SELECT PersonID, Mth, Yr, COUNT(*) as DLY_Cnt,
       RANK() OVER (PARTITION BY PersonID, Mth ORDER BY Yr DESC) as YrRnk,
       SUM(COUNT(*)) (PARTITION BY PersonId, Mth ORDER BY Yr) as DPY_Cnt
FROM #BkgSummary
GROUP BY PersonID, Mth, Yr;

You can do something similar using correlated subqueries in earlier versions:

with t as (
      SELECT PersonID, Mth, Yr, COUNT(*) as DLY_Cnt,
             RANK() OVER (PARTITION BY PersonID, Mth ORDER BY Yr DESC) as YrRnk
      FROM #BkgSummary
      GROUP BY PersonID, Mth, Yr
     )
select t.*,
       (select sum(DLY_CNT)
        from t t2
        where t.PersonID = t2.PersonId and
              t.Yr = t2.Yr and
              t.Mth >= t2.Mth
       ) as DPY_Cnt
from t;

Andere Tipps

Try this...

  WITH CTE
AS (
    SELECT ID
        , MTH
        , YR
        , COUNT(*) AS DLY_CNT
        , DENSE_RANK() OVER (ORDER BY ID, MTH) DR
    FROM A
    GROUP BY ID
        , MTH
        , YR
    )
SELECT ID
    , MTH
    , DR
    , SUM(DLY_CNT)
FROM CTE
GROUP BY ID
    , MTH
    , DR
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top