1
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
4

3 回答 3

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
于 2012-08-28T00:46:30.543 回答
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
于 2012-08-28T00:49:05.897 回答
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)
于 2012-08-28T04:03:57.557 回答