我有一组数据,该数据按部门,会计年度,会计季度以及最终总金额进行划分,如下所示。
+---------------------------------+------------+---------------+-------------+
| Department | FISCALYEAR | FISCALQUARTER | TotalAmount |
+---------------------------------+------------+---------------+-------------+
| Internal Medicine - Dermatology | 2018 | 2 | 50.00 |
| Internal Medicine - Dermatology | 2018 | 4 | 75.00 |
| Internal Medicine - Dermatology | 2019 | 1 | 135.00 |
| Internal Medicine - Dermatology | 2019 | 2 | 75.00 |
| Internal Medicine - Dermatology | 2019 | 3 | 185.00 |
| Internal Medicine - Dermatology | 2019 | 4 | 84.00 |
| Internal Medicine - Dermatology | 2020 | 1 | 85.00 |
| Internal Medicine - Dermatology | 2020 | 2 | 10.00 |
+---------------------------------+------------+---------------+-------------+
我如何添加一列以获取上一年/季度的总金额? 例如,2020财年,第二财季将显示75.00。
困难的部分是某些季度没有任何数据,因此存在差距。
我尝试了LAG()窗口函数,但是由于它不是标准偏移量,因此很难指定偏移量。
任何帮助/想法都很棒。
答案 0 :(得分:1)
this怎么样?
IF OBJECT_ID('tempdb.dbo.#YourTable', 'U') IS NOT NULL DROP TABLE #YourTable;
CREATE TABLE #YourTable(
Department VARCHAR(33) NOT NULL
,FISCALYEAR INTEGER NOT NULL
,FISCALQUARTER INTEGER NOT NULL
,TotalAmount NUMERIC(7,2) NOT NULL
);
INSERT INTO #YourTable(Department,FISCALYEAR,FISCALQUARTER,TotalAmount) VALUES ('Internal Medicine - Dermatology',2018,2,50.00);
INSERT INTO #YourTable(Department,FISCALYEAR,FISCALQUARTER,TotalAmount) VALUES ('Internal Medicine - Dermatology',2018,4,75.00);
INSERT INTO #YourTable(Department,FISCALYEAR,FISCALQUARTER,TotalAmount) VALUES ('Internal Medicine - Dermatology',2019,1,135.00);
INSERT INTO #YourTable(Department,FISCALYEAR,FISCALQUARTER,TotalAmount) VALUES ('Internal Medicine - Dermatology',2019,2,75.00);
INSERT INTO #YourTable(Department,FISCALYEAR,FISCALQUARTER,TotalAmount) VALUES ('Internal Medicine - Dermatology',2019,3,185.00);
INSERT INTO #YourTable(Department,FISCALYEAR,FISCALQUARTER,TotalAmount) VALUES ('Internal Medicine - Dermatology',2019,4,84.00);
INSERT INTO #YourTable(Department,FISCALYEAR,FISCALQUARTER,TotalAmount) VALUES ('Internal Medicine - Dermatology',2020,1,85.00);
INSERT INTO #YourTable(Department,FISCALYEAR,FISCALQUARTER,TotalAmount) VALUES ('Internal Medicine - Dermatology',2020,2,10.00);
SELECT a.Department, a.FISCALYEAR, a.FISCALQUARTER,
a.TotalAmount, b.TotalAmount AS PriorYearQuarterTotalAmount
FROM #YourTable a
LEFT JOIN #YourTable b ON a.Department = b.Department
AND a.FISCALYEAR - 1 = b.FISCALYEAR
AND a.FISCALQUARTER = b.FISCALQUARTER
答案 1 :(得分:0)
您可以使用内联查询:
select
t.*,
(
select t1.TotalAmount
from mytable t1
where t1.FiscalQuarter = t.FiscalQuarter and t1.FiscalYear = t.FiscalYear - 1
) lastTotalAmount
from mytable t
答案 2 :(得分:0)
假设您有每年的数据,请使用窗口函数:
error: No signing certificate "iOS Distribution" found: No "iOS Distribution" signing certificate matching team ID "xxx" with a private key was found. (in target 'yy')
窗口函数通常会导致最快的查询,并且比替代方法更简洁。