sql多年来的增长

sbdsn5lh  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(325)

我有一张table member_id , joined (正如《时代周刊》所说)我正试图找出如何找出年与年之间的增长率。我有

SELECT YEAR(joined) AS JoinedYear, COUNT(member_id) AS Members
FROM grp_member 
GROUP BY YEAR(joined) 
ORDER BY JoinedYear asc;

这显示了每年加入的人数,但需要使用子查询帮助查找增长。

ws51t4hk

ws51t4hk1#

只需使用一个窗口函数:

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;
dbf7pr2w

dbf7pr2w2#

通过快速的web搜索,可以从sqlservercentral中发现以下示例:获取同比增长数据将您的基本查询作为cte,并对其进行自联接以获取上一年的值:

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

在这里尝试:http://sqlfiddle.com/#!18/8a3f7/5型
年度会员同比增长20193020063202193
此输出中不包括成员总数,因为这应包括已失效或取消的成员的准备金,但这应是满足更复杂需求的简单入门。

相关问题