2013-12-13 108 views
0

我有這個表:添加三個子查詢的結果

id item_name_1 quantity 1 item_name_2 quantity_2 item_name_3 quantity_3 
----------------------------------------------------------------------------------- 
1 Apple   2   Pear   3   Orange  5 
2 Pear   1   Apple   4 
3 Orange  6 
4 Apple   1   Pear   2   Orange  3 

我想這樣的結果:

item  total 
-------------- 
Apple 7 
Pear  6 
Orange 14 

我嘗試這樣做:

SELECT 

(SELECT item_name_1, SUM(quantity_1) AS count FROM table1 
GROUP BY item_name_1) AS item, 

(SELECT item_name_2, SUM(quantity_2) AS count FROM table1 
GROUP BY item_name_2) AS item, 

(SELECT item_name_3, SUM(quantity_3) AS count FROM table1 
GROUP BY item_name_3) AS item, 

SUM(count) AS total 
FROM table1 
GROUP BY item; 

錯誤代碼:1241的操作對象含有1列(多個)

不限sugges蒸發散?

+3

對於初學者來說,你的數據庫是沒有正確歸。這是你的數據庫,還是別人的? –

+0

這是我的數據庫。我將努力使其正常化。謝謝你的建議。 – Vincevna

回答

0

當您只有一列時,您在子查詢中選擇了兩列。

像這樣的事情會得到你在找什麼:

SELECT item_name, SUM(quantity) AS quantity 
FROM 
(SELECT item_name_1 AS item_name, SUM(quantity_1) AS quantity 
FROM table1 
GROUP BY item_name_1 

UNION ALL 

SELECT item_name_2 AS item_name, SUM(quantity_2) AS quantity 
FROM table1 
GROUP BY item_name_2 

UNION ALL 

SELECT item_name_3 AS item_name, SUM(quantity_3) AS quantity 
FROM table1 
GROUP BY item_name_3) AS ABB1 
GROUP BY item_name; 
+0

超人!謝謝! – Vincevna

0

我會嘗試像這樣。

select t.item_name_1, s1+s2+s3 

from 
(
select * From 
( 
select sum(quantity_1) as s1, item_name_1 
from 
table1 
group by item_name_1 
) t1 

full outer join 

( 
select sum(quantity_2) as s2, item_name_2 
from 
table1 
group by item_name_2 
) t2 on t1.item_name_1 = t2.item_name_2 

full outer join 

( 
select sum(quantity_3) as s3, item_name_3 
from 
table1 
group by item_name_3 
) t3 on t2.item_name_2 = t3.item_name_3 

) t