再写一个数据集查询同比的值,然后用value函数按条件查询数据出来就行了。这个是简单的方式
sql server中查询当期与同期数据
SELECT
YEAR(SaleDate) AS SaleYear,
SUM(Amount) AS TotalSales,
LAG(SUM(Amount), 1) OVER (ORDER BY YEAR(SaleDate)) AS PreviousYearSales,
CASE
WHEN LAG(SUM(Amount), 1) OVER (ORDER BY YEAR(SaleDate)) IS NULL THEN NULL
ELSE (SUM(Amount) - LAG(SUM(Amount), 1) OVER (ORDER BY YEAR(SaleDate))) / LAG(SUM(Amount), 1) OVER (ORDER BY YEAR(SaleDate)) * 100
END AS YearOverYearGrowth
FROM
Sales
GROUP BY
YEAR(SaleDate)
ORDER BY
SaleYear;
---------------------------------------------------------------------------------------‘
----------------------------------------------------------------------------------------
mysql5的版本没有窗口函数取同期
SELECT
YEAR(s1.SaleDate) AS SaleYear,
SUM(s1.Amount) AS TotalSales,
(SELECT SUM(s2.Amount)
FROM Sales s2
WHERE YEAR(s2.SaleDate) = YEAR(s1.SaleDate) - 1) AS PreviousYearSales,
CASE
WHEN (SELECT SUM(s2.Amount)
FROM Sales s2
WHERE YEAR(s2.SaleDate) = YEAR(s1.SaleDate) - 1) IS NULL THEN NULL
ELSE (SUM(s1.Amount) - (SELECT SUM(s2.Amount)
FROM Sales s2
WHERE YEAR(s2.SaleDate) = YEAR(s1.SaleDate) - 1)) / (SELECT SUM(s2.Amount)
FROM Sales s2
WHERE YEAR(s2.SaleDate) = YEAR(s1.SaleDate) - 1) * 100
END AS YearOverYearGrowth
FROM
Sales s1
GROUP BY
YEAR(s1.SaleDate)
ORDER BY
SaleYear;