包括按日期和运行总计的缺失日期组

时间:2016-07-14 01:35:19

标签: mysql

我有一张如下表:

def _settings_value_changed(self, key, value):
    signal_name = "%s(PyQt_PyObject)" % key.replace("/", "_")
    self.emit(SIGNAL(signal_name), value)

我遇到了一个问题,解决了如何按天划分,总结并包含缺失日期的问题。我试图让选择看起来像这样:

transID | date | payee | amount
1       | 7/1/2016 | Balance| 100.00
2       | 7/1/2016 | Bobi | -11.11
3       | 7/4/2016 | Chris | -20.76
4       | 7/7/2016 | Erin  | -100.00
5       | 7/11/2016| Tom   | -2.11
6       | 7/11/2016| Pay   | 500.00

基本上我试图获得每个分组日期之间的所有日期并进行平衡。这将像银行帐户每天一样运作。

1 个答案:

答案 0 :(得分:0)

只需要这样的东西,也许这不是正确的方式,但对我有用:)

SELECT 
    *
FROM
    (SELECT 
        '2016-07-01' + INTERVAL a + b DAY myDate
    FROM
        (SELECT 0 a UNION SELECT 1 a UNION SELECT 2 UNION SELECT 3 UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7 UNION SELECT 8 UNION SELECT 9) d, (SELECT 0 b UNION SELECT 10 UNION SELECT 20 UNION SELECT 30 UNION SELECT 40) m
    WHERE
        '2016-07-01' + INTERVAL a + b DAY < '2016-08-01'
    ORDER BY a + b) t1
        LEFT JOIN
    (SELECT 
        COUNT(*) AS myCount, DATE(your_date_field) AS myFS
    FROM
        your_table_that_misses_dates
    GROUP BY myFS) t2 ON t1.myDate = t2.myFS order by myDate;

它会给你这样的东西: enter image description here