我目前的表格如下:
ID TYPE QUANTITY
1 A1 3
2 B1 2
3 A1 2
4 B1 8
在做完查询之后我想得到它:
ID TYPE QUANTITY SUM
1 A1 3 5
2 B1 2 10
3 A1 2 5
4 B1 8 10
SUM列由具有相同类型的项目的总和数量组成。
答案 0 :(得分:2)
我的方法是使用派生表,首先按类型汇总数量,然后将此结果与原始数据相结合:
select
t.id,
t.type,
t.quantity,
tmp.overall
from
table t join (
select
table.type,
sum(table.quantity) as overall
from
table
group by
table.type
) tmp on t.type = tmp.type
答案 1 :(得分:0)
我没有尝试过查询,但看看如果你这样做会发生什么:
SELECT
ID,
myTable.TYPE,
QUANTITY,
aaa.summy
FROM myTable
JOIN
(
SELECT
TYPE,
SUM(QUANTITY) summy
FROM myTable
GROUP BY TYPE
) aaa
ON aaa.TYPE = myTable.TYPE
答案 2 :(得分:0)
SELECT t.ID,t.TYPE,t.QUANTITY,x.SUM FROM TABLE t LEFT JOIN
(SELECT ID,TYPE,QUANTITY,SUM(QUANTITY) AS SUM FROM TABLE GROUP BY TYPE)x
ON t.type=x.type