如何计算在同一查询中计算的2个不同列的百分比差异?它甚至可能吗?
这就是我现在所拥有的:
SELECT
Year(OrderDate) AS [Year],
Count(OrderID) AS TotalOrders,
Sum(Invoice.TotalPrice) AS TotalRevenue
FROM
Invoice
INNER JOIN Order
ON Invoice.InvoiceID = Order.InvoiceID
GROUP BY Year(OrderDate);
哪个产生这个表
现在我想再增加一个同比增长的专栏,所以即使2016年到来,增长应该在那里......
编辑: 我应该澄清一下,我希望在
旁边2015,5,246.28 -> 346,15942029% ((R2015-R2014) / 2014 * 100)
答案 0 :(得分:1)
如果将现有查询保存为 qryBase ,则可以将其用作其他查询的数据源,以获得所需内容:
SELECT
q1.Year,
q1.TotalOrders,
q1.TotalRevenue,
IIf
(
q0.TotalRevenue Is Null,
Null,
((q1.TotalRevenue - q0.TotalRevenue) / q0.TotalRevenue) * 100
) AS YoY_growth
FROM
qryBase AS q1
LEFT JOIN qryBase AS q0
ON q1.Year = (q0.Year + 1);
访问可能会抱怨它"无法在设计视图" 中表示连接表达式q1.Year =(q0.Year + 1),但您仍然可以编辑SQL视图中的查询,它将起作用。
答案 1 :(得分:0)
您要找的是这样的?
Year Revenue Growth
2014 55
2015 246 4.47
2016 350 1.42
您可以将原始查询包装两次以获取两年的数字。
select orders.year, orders.orders, orders.revenue,
(select (orders.revenue/subOrders.revenue)
from
(
--originalQuery or table link
) subOrders
where subOrders.year = (orders.year-1)
) as lastYear
from
(
--originalQuery or table link
) orders
这是一个廉价的工会表示例。
select orders.year, orders.orders, orders.revenue,
(select (orders.revenue/subOrders.revenue)
from
(
select 2014 as year, 2 as orders, 55.20 as revenue
union select 2015 as year, 2 as orders, 246.28 as revenue
union select 2016 as year, 7 as orders, 350.47 as revenue
) subOrders
where subOrders.year = (orders.year-1)
) as lastYear
from
(
select 2014 as year, 2 as orders, 55.20 as revenue
union select 2015 as year, 2 as orders, 246.28 as revenue
union select 2016 as year, 7 as orders, 350.47 as revenue
) orders