获取SQL结果中列和行的总数

时间:2018-08-14 12:01:46

标签: mysql sql

我正在使用以下SQL语句从数据库中获取物流成本:

SELECT
country,
sum(Costs_Inbound), sum(Costs_Outbound)
FROM Logistics
GROUP BY country

可以找到here数据库(sqlfiddle)。到目前为止,所有这些工作正常。


现在,我希望在结果中也显示总计。因此,我尝试使用here中的以下解决方案:

SELECT country, Costs_Inbound, Costs_Outbound
FROM Logistics
UNION ALL
SELECT null,sum(country),null,sum(Costs_Inbound),null,sum(Costs_Outbound)
FROM Logistics

很遗憾,我无法使其正常工作。

您知道我的代码中哪里有错误吗?

3 个答案:

答案 0 :(得分:1)

您似乎想要:

SELECT country, Costs_Inbound, Costs_Outbound
FROM Logistics
UNION ALL
SELECT NULL, SUM(Costs_Inbound), SUM(Costs_Outbound)
FROM Logistics;

答案 1 :(得分:1)

在下面的查询中尝试以下操作:对于联合/联合,所有列号都应相等,以供选择,在查询中,列号不相同

SELECT country, Costs_Inbound, Costs_Outbound
FROM Logistics
UNION ALL
SELECT null,sum(Costs_Inbound),sum(Costs_Outbound)
FROM Logistics

http://sqlfiddle.com/#!9/2c9fa44/17

答案 2 :(得分:0)

您的代码不起作用,因为第一个子查询没有group by,并且两个查询具有不同的列数。

使用ROLLUP

SELECT country, sum(Costs_Inbound), sum(Costs_Outbound),
       (sum(Costs_Inbound) + sum(Costs_Outbound)) as in_plus_out
FROM Logistics
GROUP BY country WITH ROLLUP;

如果要在同一行中输入值,请使用JOIN

SELECT l.country, sum(l.Costs_Inbound), total.total_in, 
       sum(l.Costs_Outbound), total.total_out
FROM Logistics l CROSS JOIN
     (SELECT sum(l.Costs_Inbound) as total_in, sum(l.Costs_Outbound) as total_out
      FROM logistics l
     ) total
GROUP BY l.country, total.total_in, total.total_out;