我有一个带有struct的表销售订单:
- ItemID
- Customer
- Year
- Month
- Quantity
我想要构建报告,如:
Customer | Item | Year | Month | Quantity | The same month of the previous year quantity|
你能帮我吗?
感谢。
答案 0 :(得分:0)
您可以通过执行SELF JOIN
并加入前一年来完成此操作:
SELECT
T1.Customer,
T1.Item,
T1.Year,
T1.Month,
T1.Quantity,
T2.Quantity AS Last_year_quantity
FROM Table AS T1
LEFT JOIN Table AS T2 ON T1.Customer=T2.Customer
AND T1.Item=T2.Item
AND (T1.Year-1)=T2.Year
AND T1.Month=T2.Month;
答案 1 :(得分:0)
就像一个没有表结构或任何东西的快速模型
select a.customer, a.item, a.year, a.month, a.quantity,
(select b.quantity
from table_name b
where b.customer = a.customer
and b.item = a.item
and b.month = a.month
and b.year = a.year - 1) as prev_year_qty
from table_name a