我对sql中的Windows函数的理解仍然很薄弱,因此我正在寻求有关如何尽可能使用Windows函数回答以下问题的建议。
Q1。要从订单表中找到每个国家/地区的平均每日收入,我需要先将订单的收入汇总到每日水平,然后再获取每个国家/地区的平均收入。我可以通过子查询来做到这一点,但是可以通过Windows函数实现吗?
Q2。在同一个订单表中,我有两年的每日交易,并且想要计算2019年第一季度至2018年第一季度之间平均每日收入的变化百分比。我是通过在两个子查询的where子句中手动配置日期来做到这一点的,但是可以以某种方式使用lag函数吗?
谢谢!
-- Q1 without windows function
select country, avg(d)
from
(select country, date, sum(revenue) as d
from orders
group by country, date)
group by country
-- Q2 two separate subqueries to retrieve information for both periods
SELECT ....
FROM
(SELECT country, date, SUM(revenue) AS 2019_daily_net_revenue
FROM orders
WHERE date BETWEEN “1/1/2019” AND “31/3/2019”
GROUP BY country, date) AS 2019_T
INNER JOIN
(SELECT country, date, SUM(revenue) AS 2018_daily_net_revenue
FROM orders
WHERE date BETWEEN “1/1/2018” AND “31/3/2018”
GROUP BY country, date) AS 2018_T
ON 2018_T.country = 2019_T.country
GROUP BY ....