MySQL按总和值分组到其他列

时间:2019-06-10 16:50:28

标签: mysql sql

大家好!我有一个数据库Table1,它有3列。说明,数量和transactionid。

    Description              qty          transactionid
    Bed sheet                 1               1
    Towel                     1               1
    Bed sheet                 1               2
    Towel                     1               2
    Bed sheet                 1               1
    Towel                     1               1
    Bed sheet                 1               2
    Towel                     1               2

我希望输出是这样的。

    Description            qty            transactionid
    Bed sheet                2               1
    Towel                    2               1
    Bed sheet                2               2
    Towel                    2               2

这是我的代码:         SELECT描述,SUM(qty),来自表1 GROUP BY transactionid的transactionid

感谢您的帮助。 天哪

2 个答案:

答案 0 :(得分:0)

您需要按交易ID进行分组,说明

SELECT Description, SUM(qty) qty, transactionid 

FROM Table1 
GROUP BY transactionid, Description

答案 1 :(得分:0)

    SELECT DISTINCT DESCRIPTION, COUNT(QTY) AS [QTY], TRANSACTIONID
    FROM TABLE1
    GROUP BY DESCRIPTION, TRANSACTIONID

查询中未聚合的任何列都必须分组或聚合。

相关问题