SELECT YEAR(joined) AS JoinedYear,
COUNT(*) AS Members,
(-1 + COUNT(*) * 1.0 / LAG(COUNT(*)) OVER (ORDER BY YEAR(joined))) as growth_rate
FROM grp_member
GROUP BY YEAR(joined)
ORDER BY JoinedYear asc;
WITH Growth
AS (
SELECT YEAR(joined) AS JoinedYear, COUNT(member_id) AS Members
FROM grp_member
GROUP BY YEAR(joined)
ORDER BY JoinedYear asc
)
SELECT curYear.JoinedYear AS [Year], curYear.[Members]
FROM Growth curYear
LEFT JOIN Growth prevYear ON curYear.JoinedYear = prevYear.JoinedYear + 1
ORDER BY curYear.JoinedYear
2条答案
按热度按时间ws51t4hk1#
只需使用一个窗口函数:
dbf7pr2w2#
通过快速的web搜索,可以从sqlservercentral中发现以下示例:获取同比增长数据将您的基本查询作为cte,并对其进行自联接以获取上一年的值:
在这里尝试:http://sqlfiddle.com/#!18/8a3f7/5型
年度会员同比增长20193020063202193
此输出中不包括成员总数,因为这应包括已失效或取消的成员的准备金,但这应是满足更复杂需求的简单入门。