我有这张桌子:
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列
有什么建议吗?
答案 0 :(得分: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
答案 1 :(得分: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;