我使用以下SQL从数据库中获取物流成本:
SELECT country, sum(Costs_Inbound), sum(Costs_Storage), sum(Costs_Outbound),
(sum(Costs_Inbound) + sum(Costs_Storage) + sum(Costs_Outbound)) as Total
FROM Logistics
GROUP BY country WITH ROLLUP;
可以找到here,其中包含数据库的SQL Fiddle
。
到目前为止,所有这些工作正常。
现在,我想知道是否可以通过引用第一行中的列表达式来简化第二个sum语句,因为-如您所见-现在,我将第一行中的每个列表达式复制到第二行中。 / p>
答案 0 :(得分:1)
您可以使用单个SUM()
对其进行简化:
SELECT country, SUM(Costs_Inbound), SUM(Costs_Storage), SUM(Costs_Outbound),
SUM(Costs_Inbound + Costs_Storage + Costs_Outbound) as Total
FROM Logistics
GROUP BY country WITH ROLLUP;