按月列出分组数据,包括没有结果的月份

时间:2017-12-01 20:09:20

标签: mysql

Hello社区以下查询添加每个活动状态的出现次数,然后按月对其进行分组

import sys

from PyQt5.QtWidgets import *
from PyQt5.QtCore import *

class Widget(QWidget):
    def __init__(self, *args, **kwargs):
        QWidget.__init__(self, *args, **kwargs)
        self.tree = QTreeWidget(self)
        self.stack = QStackedWidget(self)
        lay = QHBoxLayout(self)
        lay.addWidget(self.tree)
        lay.addWidget(self.stack)

        for key, value in TreeList.items():
            root = QTreeWidgetItem(self.tree, [key])
            for val in value:
                item = QTreeWidgetItem([val])
                root.addChild(item)
                widget = QLabel(val,  self)
                ix = self.stack.addWidget(widget)
                item.setData(0, Qt.UserRole, ix)
        self.tree.expandAll()
        self.tree.itemClicked.connect(self.onItemClicked)

    def onItemClicked(self, item, column):
        val = item.data(0, Qt.UserRole)
        if val is not None:
            self.stack.setCurrentIndex(val)

TreeList = ({

    'Header1': ((
        'Item11',
        'Item12',
    )),

    'Header2': ((
        'Item21',
        'Item22'
    ))
})

if __name__ == '__main__':
    app = QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())

所以我得到以下结果

enter image description here

我想在这个结果中添加没有数据的月份,并用零自动完成状态总和

enter image description here

我分享了此sqlfiddle

我发现这个answer类似的情况,但我无法理解如何将它应用于我呈现给你的案例

非常感谢您的帮助

1 个答案:

答案 0 :(得分:1)

您可以使用日期表(子查询)和LEFT JOIN

select
    s.name month,
    s.m pivot,
    sum(case when a.state = 'created' then 1 else 0 end) created,
    sum(case when a.state = 'notified' then 1 else 0 end) notified,
    sum(case when a.state = 'confirmed' then 1 else 0 end) confirmed,
    sum(case when a.state = 'approved' then 1 else 0 end) approved,
    sum(case when a.state = 'authorized' then 1 else 0 end) authorized,
    sum(case when a.state = 'attended' then 1 else 0 end) attended,
    sum(case when a.state = 'canceled' then 1 else 0 end) canceled,
    count(a.id) as total
from (SELECT  1 m, 'Jan' AS name 
      UNION SELECT 2, 'Feb' 
      UNION SELECT 3, 'Mar'
      UNION ...) s
LEFT JOIN activities a
  ON s.m = month(date_created)
  --AND s.y = year(date_created)   -- if needed 
group by 1
order by pivot desc;

<强> DBFiddle Demo