MySQL使用Group By多列的总和

时间:2017-06-21 14:23:52

标签: mysql group-by sum

以下查询:

class UiMainWindow(QtGui.QMainWindow):
    def __init__(self, parent=None):
        super(UiMainWindow, self).__init__(parent)
        #codes
        self.series_lineEdit = QtGui.QLineEdit()
        a = UiSeries(self, str(self.series_lineEdit.text()))


class UiSeries(QtGui.QWidget):
    def __init__(self, series_name, parent = None):
        super(UiSeries, self).__init__(parent)
        self.series_name = series_name
        print(series_name)

产地:

SELECT `brand`,
       count(*) * `denomination` AS 'total'
FROM `inventory`
WHERE `owner` = 'owner-one'
    AND `currency` = 'GBP'
    AND `activated_at` IS NULL
    AND `expires_at` >= '2018-06-21'
GROUP BY `owner`,
         `brand`,
         `currency`,
         `denomination`

我想要的是进一步按项目分组并总计总数,以便输出如下:

| brand     | total |
|-----------|-------|
| brand-one | 3000  |
| brand-one | 8000  |
| brand-two | 10000 |

数据:

Sample data

1 个答案:

答案 0 :(得分:2)

你获得3条记录的原因是该组包含面额。如果我们改变逻辑以便我们求和而不是count(*)*面额,那么我们可以得到你的两个记录。 (如果你从小组中删除了面额)......但也许我错过了一些东西。

SELECT `brand`,
       Sum(`denomination`) AS 'total'
FROM `inventory`
WHERE `owner` = 'owner-one'
  AND `currency` = 'GBP'
  AND `activated_at` IS NULL
  AND `expires_at` >= '2018-06-21'
GROUP BY `owner`,
         `brand`,
         `currency`