我有4个不同列的表。但是在4个表中我有两个常见的列。一个Vendor_id和Stock.This Vendor_id可以在所有4个表中重复。 现在ny要求是我要在所有4个表中汇总与所有供应商ID相关的所有股票。例如:
表一
+----------+-------------+
|vendor_id | stoclk |
+----------+-------------+
| 1234 | 75.00 |
+----------+-------------+
| 1234 | 75.00 |
+----------+-------------+
| 789 | 75.00 |
+----------+-------------+
表二
+----------+-------------+
|vendor_id | stoclk |
+----------+-------------+
| 1234 | 5.00 |
+----------+-------------+
| 2389 | 15.00 |
+----------+-------------+
| 789 | 15.00 |
+----------+-------------+
我的deisred out put将
+----------+-------------+
|vendor_id | stoclk |
+----------+-------------+
| 1234 | 155.00 |
+----------+-------------+
| 2389 | 15.00 |
+----------+-------------+
| 789 | 90.00 |
+----------+-------------+
对于我使用以下查询。
SELECT vendor_id,SUM(stock) FROM ( SELECT vendor_id, stock FROM hs_tab1 UNION ALL SELECT vendor_id, stock FROM hs_tab2 UNION ALL )a
但我只获得一个供应商ID和总数或这样的股票
+----------+-------------+ |vendor_id | stoclk | +----------+-------------+ | 1234 | 260.00 | +----------+-------------+
请告诉我一些我做错的事情?
答案 0 :(得分:1)
试试这个: -
SELECT vendor_id,SUM(stock)
FROM ( SELECT vendor_id, stock FROM hs_tab1
UNION ALL
SELECT vendor_id, stock FROM hs_tab2
)a
GROUP BY vendor_id;