如何基于另一列汇总列?

时间:2016-06-08 03:07:17

标签: mysql

我有一张这样的表:

  ID     Item   Total 
P-001   ATK001  1500
P-002   ATK001  1750
P-002   ATK002  1250
P-003   ATK001  175
P-003   ATK002  350
P-003   ATK003  400
P-003   CTK001  750
P-003   CTK002  750
P-005   ATK004  500
P-005   ATK117  475
P-005   CTK009  1200
P-005   ATK001  400
P-005   ATK002  125

我想根据'Item'列总结'Total'列。我已经创建了一些mysql查询,输出是这样的:

P-001   ATK001  3825
P-002   ATK002  1725
P-003   ATK003  400
P-005   ATK004  500
P-005   ATK117  475
P-003   CTK001  750
P-003   CTK002  750
P-005   CTK009  1200

我想要的输出是:

ID      Item   Total
P-001   ATK001  3825
P-002   ATK001  3825
P-002   ATK002  1725
P-003   ATK001  3825
P-003   ATK002  1725
P-003   ATK003  400
P-003   CTK001  750
P-003   CTK002  750
P-005   ATK004  500
P-005   ATK117  475
P-005   CTK009  1200
P-005   ATK001  3825
P-005   ATK002  1725

感谢您的帮助:)

3 个答案:

答案 0 :(得分:5)

试试这个;)

SQL Fiddle

MySQL 5.6架构

CREATE TABLE table1
    (`ID` varchar(5), `Item` varchar(6), `Total` int)
;

INSERT INTO table1
    (`ID`, `Item`, `Total`)
VALUES
    ('P-001', 'ATK001', 1500),
    ('P-002', 'ATK001', 1750),
    ('P-002', 'ATK002', 1250),
    ('P-003', 'ATK001', 175),
    ('P-003', 'ATK002', 350),
    ('P-003', 'ATK003', 400),
    ('P-003', 'CTK001', 750),
    ('P-003', 'CTK002', 750),
    ('P-005', 'ATK004', 500),
    ('P-005', 'ATK117', 475),
    ('P-005', 'CTK009', 1200),
    ('P-005', 'ATK001', 400),
    ('P-005', 'ATK002', 125)
;

查询1

select t1.ID, t1.Item, t2.Total
from table1 t1
inner join(
    select Item, sum(Total) as Total from table1 group by Item
) t2 on t1.Item = t2.Item

<强> Results

|    ID |   Item | Total |
|-------|--------|-------|
| P-001 | ATK001 |  3825 |
| P-002 | ATK001 |  3825 |
| P-002 | ATK002 |  1725 |
| P-003 | ATK001 |  3825 |
| P-003 | ATK002 |  1725 |
| P-003 | ATK003 |   400 |
| P-003 | CTK001 |   750 |
| P-003 | CTK002 |   750 |
| P-005 | ATK004 |   500 |
| P-005 | ATK117 |   475 |
| P-005 | CTK009 |  1200 |
| P-005 | ATK001 |  3825 |
| P-005 | ATK002 |  1725 |

答案 1 :(得分:2)

SELECT
    T1.ID,
    T2.Item,
    Sum(T2.Total)
FROM
    TABLE T1,
    TABLE T2
GROUP BY    T1.ID, T2.Item;

答案 2 :(得分:1)

SELECT
    id,
    item,
    (
        SELECT
            sum(total)
        FROM
            items i2
        WHERE
            i1.item = i2.item
    ) AS total
FROM
    items i1