选择每个月的分组日期范围的销售量(SQLite)

问题描述 投票:0回答:1

我需要进行查询,以获取没有销售的月份。 (SQLITE)

表格

| id |    date    | total | id_user |
|  1 | 2019-01-01 | 400   |    1    |
|  2 | 2019-01-09 | 600   |    1    |
|  3 | 2019-08-01 | 100   |    1    |
|  4 | 2019-08-08 | 500   |    1    |
|  5 | 2019-08-15 | 1400  |    1    |
|  6 | 2019-09-01 | 7000  |    1    |

我有这个查询

SELECT 
    sum(venta.total) as Total,
    strftime('%m',venta.fecha_venta) as Month, 
    strftime('%Y',venta.fecha_venta) as Year
FROM venta 
LEFT JOIN VENTA_ESPECIE 
WHERE strftime('%Y', date('now')) == strftime('%Y',venta.fecha_venta) 
AND venta.fecha_venta 
BETWEEN '2019-01-30' AND '2019-10-30'
 GROUP by Month ;

结果

| Total | Month | Year |
| 1000  |  01   | 2019 |
| 2000  |  08   | 2019 |
| 7000  |  09   | 2019 |

我想得到这个结果

| Total | Month | Year |
| 1000  |  01   | 2019 |
|   0   |  02   | 2019 |
|   0   |  03   | 2019 |
|   0   |  04   | 2019 |
|   0   |  05   | 2019 |
|   0   |  06   | 2019 |
|   0   |  07   | 2019 |
| 2000  |  08   | 2019 |
| 7000  |  09   | 2019 |
|   0   |  10   | 2019 |

重要的是,它可以在两个日期之间更改

typescript sqlite typeorm
1个回答
0
投票

我相信以下内容将满足您的要求:-

WITH cte_dates(dates) /*CTE generates a list of dates in the given range */ AS 
    (
        SELECT '2019-01-01' /*<<<< start of range */
        UNION ALL SELECT date(dates,'+1 Months') FROM cte_dates WHERE dates <= '2019-10-01' /*<<<< end of range */
    )

SELECT 
    coalesce(
        (
            SELECT sum(total) 
        FROM venta WHERE strftime('%Y',date) = strftime('%Y',dates) AND strftime('%m',date) = strftime('%m',dates)
        )
        ,0 /* 0 instead of null for coalesce */
    ) AS Total, 
    strftime('%m',dates) AS Month, 
    strftime('%Y',dates) AS Year 
FROM cte_dates
;
  • 请注意,这是基于表而不是不反映表的查询。

即通风口表为:-

enter image description here

结果是:-

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.