SQL - 使用First&amp ;;进行年度计算。下一个记录

时间:2017-02-24 05:20:30

标签: sql

我正在使用此服务器进行测试:

https://www.w3schools.com/sql/trysql.asp?filename=trysql_select_all

问题:

我希望在名为“YOY'”的新专栏中计算年度增长率。使用一个查询的绝对值使用强制转换函数。

SELECT Orders.EmployeeID, Year(Orders.OrderDate) AS 'Year', COUNT(Year(Orders.OrderDate)) AS '# of Orders', 'CAL' AS 'YOY'
FROM Orders
WHERE Orders.EmployeeID = 4 OR Orders.EmployeeID = 3 OR Orders.EmployeeID = 1
GROUP BY Year(Orders.OrderDate), Orders.EmployeeId
ORDER BY Orders.EmployeeId DESC

输出:

  EmployeeID    'Year'  '# of Orders'   'YOY'
  4              1996       31           CAL 
  4              1997       9            CAL
  3              1996       18           CAL
  3              1997       13           CAL
  1              1996       26           CAL
  1              1997       3            CAL

Here Is How It Looks So Far 预期产出:

  EmployeeID    'Year'  '# of Orders'   'YOY'
  4              1996       31           70% 
  4              1997       9            
  3              1996       18           28%
  3              1997       13           
  1              1996       26           88%
  1              1997       3            

1 个答案:

答案 0 :(得分:0)

您可以尝试以下方法: 已修改的查询:

select oagg1.EmployeeID,oagg1.yr,oagg1.cnt,oagg2.cnt next_yr_qty,
        (((oagg1.cnt-oagg2.cnt)*100)/oagg1.cnt ) yoy
from (SELECT EmployeeID,substr(orderDate,1,4)yr,count(*) cnt
        FROM [Orders] o
        where EmployeeID in (1,3,4)
        group by EmployeeID,substr(orderDate,1,4))oagg1
left outer join         
    (SELECT EmployeeID,substr(orderDate,1,4)yr,count(*) cnt
        FROM [Orders] o
    where EmployeeID in (1,3,4)
    group by EmployeeID,substr(orderDate,1,4))oagg2
on oagg1.EmployeeID=oagg2.EmployeeID
and cast(oagg1.yr as int)=cast(oagg2.yr as int)-1
order by 1 desc

基本上你只需要自己加入订单表来选择去年的订单数量。