如果你有样本数据:
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 <>在这里拨弄
关键是我使用的是MONTHYEAR别名,并在PURCHASEDATE之前订购...感谢您的详细回答