如何创建在同一列中数字之间存在百分比差异的列

时间:2019-07-03 21:27:22

标签: sql sqlite

我是SQL的新手,我想一种应用我所知道的好方法就是尝试一个发现的小项目。我已经能够找到年收入,但是提示要求上一年的百分比变化。我似乎无法弄清楚如何添加具有此百分比变化的列。

我尝试使用ISNULL,DATEDIFF和LAG,但我认为我没有正确使用它。

以下是创建表的代码:

SELECT CAST(strftime('%Y', InvoiceDate) AS integer) AS YearOfSale, SUM(Total) AS TotalRev
FROM invoices
GROUP BY 1;

还有我尝试用来创建新列的代码:

WITH yearlySales AS (
    SELECT CAST(strftime('%Y', InvoiceDate) AS integer) AS YearOfSale, SUM(Total) AS TotalRev
    FROM invoices
    GROUP BY 1
)
SELECT X.*, ISNULL(DATEDIFF(year, X.PREVDATE, X.YearOfSales),0) AS YearDiff
FROM (SELECT y.*, LAG(y.YearlySales) OVER( ORDER BY YEARLYSALES) AS PREVDATE  FROM yearlySales y )X;

我希望该列如下所示:

+------------+----------+-------------+
| YearOfSale | TotalRev | PercentDiff |
+------------+----------+-------------+
| 2009       | 449.46   | 7.12        |
+------------+----------+-------------+
| 2010       | 481.45   | -2.46       |
+------------+----------+-------------+
| 2011       | 469.58   | 1.69        |
+------------+----------+-------------+
| 2012       | 477.53   | -5.64       |
+------------+----------+-------------+
| 2013       | 450.58   | null        |
+------------+----------+-------------+

我的代码甚至都不会在SQL Server的DB浏览器上编译。

1 个答案:

答案 0 :(得分:0)

这是您想要的吗?

SELECT CAST(strftime('%Y', InvoiceDate) AS integer) AS YearOfSale,
       SUM(Total) AS TotalRev,
       SUM(TOTAL) / LAG(SUM(TOTAL)) OVER (ORDER BY MIN(InvoiceDate)) - 1
FROM invoices
GROUP BY 1