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

np8igboo  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(363)

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

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

数据库 (sqlfiddle) 可以在这里找到。到目前为止,这一切都很好。
现在,我希望在结果中,列和行的总数也显示出来。因此,我尝试从这里开始采用以下解决方案:

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

不幸的是,我不能让它工作。
你知道我的密码哪里出错了吗?

vojdkbi0

vojdkbi01#

尝试下面的查询:对于union/union,所有列no都应相等以供选择,在您的查询中,列no不相同

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

http://sqlfiddle.com/#!2017年9月29日

lnxxn5zx

lnxxn5zx2#

您的代码无法工作,因为第一个子查询没有 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;
zvokhttg

zvokhttg3#

你似乎想要:

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

相关问题