我创建了一个表,以显示年和月的总收入,我想在表中添加一列,以显示之后的总收入是否大于之前的10%。
我尝试过:
select DATEPART(YEAR, OrderDate) AS OrderYear,
DATEPART(MONTH, OrderDate) AS OrderMonth,
ROUND(SUM(UnitPrice*Quantity-Discount),2) AS Total_Revenue,
case when SUM(UnitPrice*Quantity-Discount) > 10 THEN '>10' ELSE '<=10' end my_col
FROM [Order Details], Orders
WHERE Orders.OrderID = [Order Details].OrderID
GROUP BY DATEPART(YEAR, OrderDate), DATEPART(MONTH, OrderDate)
ORDER BY DATEPART(YEAR, OrderDate), DATEPART(MONTH, OrderDate)
我知道了
我需要获得:
问题是我需要计算上一行与当前行之间的变化百分比,我该怎么做?
答案 0 :(得分:0)
您可以使用LAG()
。我会推荐一个子查询,以简化命名:
select ym.*,
(case when Total_Revenue > 1.1 * lag(Total_Revenue) over (order by orderyear, ordermonth)
then 'Reached'
else 'Missed'
end)
from (select DATEPART(YEAR, o.OrderDate) AS OrderYear,
DATEPART(MONTH, o.OrderDate) AS OrderMonth,
ROUND(SUM(od.UnitPrice * od.Quantity - od.Discount), 2) AS Total_Revenue
from [Order Details] od join
Orders o
on o.OrderID = od.OrderID
group by DATEPART(YEAR, o.OrderDate), DATEPART(MONTH, o.OrderDate)
) ym
order by orderyear, ordermonth;
注意:
FROM
子句中使用逗号。JOIN
语法。