获取三个表中某一列的总和并知道它来自哪个表

问题描述 投票:0回答:2

我有一个奇怪的问题。我有三个表,每个表都有不同的信息,但有一些常见的列。我想从表中得到总和,但我也想知道数据来自哪个表。我可以执行以下操作并获得总和,但如何知道它来自哪个表?

select 
    CustName, CustNumber, cost, sum(QUANTITY) as total 
from 
    (select CustName, CustNumber, cost, QUANTITY from table1 
     union all
     select CustName, CustNumber, cost, QUANTITY from table2 
     union all
     select CustName, CustNumber, cost, QUANTITY from table3) x
     
WHERE CustNumber = '894047001034' AND CustName = 'Joseph Smythe'
group by CustName;
mysql union
2个回答
0
投票

这是未经测试的代码,因此可能需要进行一些调整。

您可以将表名添加为查询中的额外列,然后将表名添加到外部选择中;

select 
    CustName, CustNumber, cost, sum(QUANTITY) as total, table_name
from 
    (select CustName, CustNumber, cost, QUANTITY, "table1" as table_name from table1 
     union all
     select CustName, CustNumber, cost, QUANTITY, "table2" as table_name from table2 
     union all
     select CustName, CustNumber, cost, QUANTITY, "table3" as table_name from table3) x
     
WHERE CustNumber = '894047001034' AND CustName = 'Joseph Smythe'
group by CustName;

0
投票
SELECT
CustName, CustNumber, cost, sum(QUANTITY) as total,
SUM(CASE WHEN table_name = "table1" THEN QUANTITY ELSE 0 END) as total1,
SUM(CASE WHEN table_name = "table2" THEN QUANTITY ELSE 0 END) as total2,
SUM(CASE WHEN table_name = "table3" THEN QUANTITY ELSE 0 END) as total3
FROM
(
   SELECT CustName, CustNumber, cost, QUANTITY, "table1" as table_name 
   FROM table1 
   union all
   SELECT CustName, CustNumber, cost, QUANTITY, "table2" as table_name 
   FROM table2
   union all
   SELECT CustName, CustNumber, cost, QUANTITY, "table3" as table_name 
) x
WHERE CustNumber = '894047001034' AND CustName = 'Joseph Smythe'
GROUP BY CustName, CustNumber, cost;
© www.soinside.com 2019 - 2024. All rights reserved.