Warm tip: This article is reproduced from serverfault.com, please click

sql-如何按月和年分组?

(sql - How to group by month and year?)

发布于 2020-11-28 09:48:21

我有一个带有日期列PURCHASEDATE的表PURCHASE,其格式为DATE。我正在尝试按月份和年份对购买进行分组。为此,我尝试:

SELECT 
TO_CHAR(PURCHASEDATE, 'MM YYYY') AS MONTHYEAR 
FROM PURCHASE
GROUP BY TO_CHAR(PURCHASEDATE, 'MM YYYY');

我也尝试过,GROUP BY EXTRACT(MONTH FROM PURCHASEDATE), EXTRACT(YEAR FROM PURCHASEDATE)但都没有奏效。

我对SQL查询:S感到生锈。

编辑

表簇

在此处输入图片说明

谢谢你!

Questioner
Juan Piza Ferra
Viewed
0
MT0 2020-11-28 17:58:41

如果你有样本数据:

CREATE TABLE purchase ( purchasedate ) AS
SELECT DATE '2019-01-01' + LEVEL - 1 FROM DUAL CONNECT BY LEVEL <= 5 UNION ALL
SELECT DATE '2019-02-01' + LEVEL - 1 FROM DUAL CONNECT BY LEVEL <= 3 UNION ALL
SELECT DATE '2020-01-01' + LEVEL - 1 FROM DUAL CONNECT BY LEVEL <= 3 UNION ALL
SELECT DATE '2020-02-01' + LEVEL - 1 FROM DUAL CONNECT BY LEVEL <= 2 UNION ALL
SELECT DATE '2020-03-01' + LEVEL - 1 FROM DUAL CONNECT BY LEVEL <= 4 UNION ALL
SELECT DATE '2020-04-01' + LEVEL - 1 FROM DUAL CONNECT BY LEVEL <= 1;

然后,你可以使用查询:

SELECT TO_CHAR(PURCHASEDATE, 'MM YYYY') AS monthyear,
       COUNT(*) AS frequency
FROM   PURCHASE
GROUP BY
       TO_CHAR(PURCHASEDATE, 'MM YYYY');

哪个输出:

MONTHYEAR | 频率
:-------- | --------:
2020年3月| 4
2019年1月| 5
2020年1月| 3
2020年2月| 2个
2019年2月| 3
2020年4月| 1个

或者,你可以使用TRUNC

SELECT TRUNC(PURCHASEDATE,'MM') AS monthyear,
       COUNT(*) AS frequency
FROM   PURCHASE
GROUP BY
       TRUNC(PURCHASEDATE,'MM');

哪个输出:

MONTHYEAR | 频率
:------------------ | --------:
2020-03-01 00:00:00 | 4
2020-04-01 00:00:00 | 1个
2020-02-01 00:00:00 | 2个
2020-01-01 00:00:00 | 3
2019-01-01 00:00:00 | 5
2019-02-01 00:00:00 | 3

或者,你可以使用EXTRACT

SELECT EXTRACT( YEAR FROM PURCHASEDATE) AS year,
       EXTRACT( MONTH FROM PURCHASEDATE) AS month,
       COUNT(*) AS frequency
FROM   PURCHASE
GROUP BY
       EXTRACT( YEAR FROM PURCHASEDATE),
       EXTRACT( MONTH FROM PURCHASEDATE);

哪个输出:

年| MONTH | 频率
---:| ----:| --------:
2019 | 1 | 5
2020 | 1 | 3
2020 | 2 | 2个
2020 | 4 | 1个
2019 | 2 | 3
2020 | 3 | 4

db <>在这里拨弄