计算跨越多个日期范围的记录

时间:2012-08-28 00:40:54

标签: sql sql-server database

ACCOUNT   Amount     DATE
1     50        01-2010
1     100       03-2010
1     100       02-2011
2     100       01-2011
2     50        05-2011
2     50        09-2011
3     100       03-2012
3     100       03-2013

是否有一个查询结构可以让我计算跨越当前和过去一年的不同帐户?例如,账户1在2011年和2010年有金额,因此应在2011年计算一次。账户2仅在2011年有金额,因此当账户3在2013年和2012年有金额时它不会被计算,因此它被计为1 2013年:

 2010   2011    2012    2013                
 0      1       0       1

3 个答案:

答案 0 :(得分:1)

首先,您需要知道帐户数据的年份:

select account, year(date) as yr
from t
group by account, year(date)

接下来,您需要查看两年是否按顺序进行。你可以在2012年以滞后/领先的方式做到这一点。相反,我们只使用自我加入:

with ay as (
     select account, year(date) as yr
     from t
     group by account, year(date)
    )
select ay.account, ay.yr
from ay join
     ay ayprev
     on ay.account = ayprev.account and
        ay.yr = ayprev.yr + 1

接下来,如果您想按年度计算帐户数量,只需将其计入聚合:

with ay as (
     select account, year(date) as yr
     from t
     group by account, year(date)
    )
select yr, count(*) as numaccounts
from (select ay.account, ay.yr
      from ay join
           ay ayprev
           on ay.account = ayprev.account and
              ay.yr = ayprev.yr + 1
     ) ayy
group by yr

答案 1 :(得分:1)

假设您有一个记录ID(称为此ID)

SELECT COUNT(*),Year FROM Table t3
INNER JOIN (
   SELECT record_id, Year(t1.Date) as Year FROM Table t1
   INNER JOIN Table t2
   WHERE Year(t1.Date)-1=Year(t2.Date) AND t1.Account == t2.Account
) x ON x.record_id = t3.record_id
GROUP BY Year

答案 2 :(得分:0)

使用以下查询:

SELECT YEAR(T1.Date) AS D, COUNT(*) AS C
FROM YourTable AS T1
INNER JOIN YourTable T2 ON T2.Account = T1.Account AND YEAR(T2)=YEAR(T1)+1
GROUP BY T1.Account, YEAR(T1.Date)