让我们知道我有这个table_1:
Year Item Qty_sold
2013 1 3
2013 2 2
2013 3 5
2014 1 2
2014 2 3
我会做这样的事情
select year , sum(Qty_sold) as Quantity
from table_1 inner join table_2 on .... inner join table_n
where Year = 2014
最终结果主要取决于按年度划分的过滤器,但还有其他表格。
但结果我需要这样的东西:
Year Quantity Diff_Percentage
2014 5 0.5
因为在上一年(2013年),所售商品的最终数量为10个。
此致
答案 0 :(得分:0)
你似乎想要这样的东西:
select year, sum(Qty_sold) as Quantity,
lag(sum(qty_sold)) over (order by year) as prev_Quantity,
(1 - Quantity / lag(sum(qty_sold)) over (order by year)) as diff_percentage
from table
group by Year;
当然,这会返回所有年份的信息。如果您真的只想要2014年和2013年,那么使用条件聚合:
select year,
sum(case when year = 2014 then Qty_sold end) as Quantity_2014,
sum(case when year = 2013 then Qty_sold end) as Quantity_2013,
(1 - sum(case when year = 2014 then Qty_sold end)/
sum(case when year = 2013 then Qty_sold end)
) as diff_percentage
from table
where Year in (2013, 2014);
我有点猜测diff_percentage
的公式,但我认为这就是你想要的。
答案 1 :(得分:0)
根据您的要求,请尝试此
select t.year,qty, (1-qty/prev_qty)
from
(select year, sum(Qty_sold) as qty,
lag(sum(qty_sold)) over (order by year) as prev_qty
from tbl group by Year) t where t.year=in_year --in_year whichever year record you want.
希望它适合你。