AVG
与上一年相比记录增加
SELECT TO_CHAR (Application_Date, 'yyyy'),
COUNT (*)
FROM Services
GROUP BY TO_CHAR (Application_Date, 'yyyy')
ORDER BY 1 DESC;
AVG
与上一年相比记录增加
示例:
2018 ----- 3000 records - 50% increase
2017 ----- 2000 records - 100% increase
2016 ----- 1000 records - 0% increase
答案 0 :(得分:2)
假设参考平均值是一条红色的鲱鱼,而您的35%的示例是一个错字...
您要比较两行中的值,因此可以使用lag()
函数通过以下命令查看上一年的数据:
LAG(COUNT(*)) OVER (ORDER BY TO_CHAR (Application_Date, 'yyyy'))
然后使用当年和上一年的计数正常计算百分比变化:
SELECT TO_CHAR (Application_Date, 'yyyy') AS year,
COUNT(*) AS year_count,
100 * (COUNT(*) - LAG(COUNT(*)) OVER (ORDER BY TO_CHAR (Application_Date, 'yyyy')))
/ LAG(COUNT(*)) OVER (ORDER BY TO_CHAR (Application_Date, 'yyyy')) AS percentage_change
FROM Services
GROUP BY TO_CHAR (Application_Date, 'yyyy')
ORDER BY 1 DESC;
YEAR YEAR_COUNT PERCENTAGE_CHANGE
---- ---------- -----------------
2018 5000 25
2017 4000 0
2016 4000
您可以根据需要设置格式的计算值(例如,是否希望将%符号用作结果的一部分,例如将其设置为字符串,然后不清楚),并且可以使用合并替换第一年的空值如果需要,则为零。
您还可以使用CTE或内联视图仅进行一次滞后:
SELECT year,
year_count,
100 * (year_count - prev_year_count) / prev_year_count AS percentage_change
FROM (
SELECT TO_CHAR (Application_Date, 'yyyy') AS year,
COUNT(*) AS year_count,
LAG(COUNT(*)) OVER (ORDER BY TO_CHAR (Application_Date, 'yyyy')) AS prev_year_count
FROM Services
GROUP BY TO_CHAR (Application_Date, 'yyyy')
)
ORDER BY 1 DESC;
个人使用年份值时,我倾向于将它们视为数字而不是字符串,因此我将使用提取:
select year,
year_count,
100 * (year_count - prev_year_count) / prev_year_count as percentage_change
from (
select extract(year from application_date) as year,
count(*) as year_count,
lag(count(*)) over (order by extract(year from application_date)) as prev_year_count
from services
group by extract(year from application_date)
)
order by 1 desc;
YEAR YEAR_COUNT PERCENTAGE_CHANGE
---------- ---------- -----------------
2018 5000 25
2017 4000 0
2016 4000