SQL将列添加到表的另一个列和行

时间:2019-05-01 08:29:33

标签: sql sql-server northwind

我创建了一个表,以显示年和月的总收入,我想在表中添加一列,以显示之后的总收入是否大于之前的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)

我知道了

this document

我需要获得:

enter image description here

问题是我需要计算上一行与当前行之间的变化百分比,我该怎么做?

1 个答案:

答案 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语法。
  • 使用表别名,这是表名称的缩写。
  • 限定所有列引用,特别是当您的查询引用多个表时。