小编典典

SQL分组依据-计算每月/每年的记录,插入时出错-无效的月份

sql

我有以下示例数据:

Country | Members   | Joined
USA     | 250       | 1/1/2012
USA     | 100       | 1/8/2012
Russia  | 75        | 1/20/2012
USA     | 150       | 2/10/2012

当我查询此数据时,我想汇总给定月份中的所有记录。查询结果如下所示:

Country | Members   | Joined
USA     | 350       | 1/2012
Russia  | 75        | 1/2012
USA     | 150       | 2/2012

作为一个足够简单的选择:

select country, count(*) as members , to_char(trunc(joined), 'MM-YYYY')
from table
group by country, to_char(trunc(joined), 'MM-YYYY')

该查询将以我想要的格式提供数据,但是我的问题是,当我将其插入到新的数据透视表中时,由于在select语句中将to_char()放置在DATETIME列中而出现错误(错误:ORA-01843-无效月份)

当我将选择中的to_char()更改为to_date()时,它仍然不起作用(相同的错误,ORA-01843-无效的月份):

select country, count(*) as members, to_date(trunc(joined), 'MM-YYYY')
from table
group by country, to_date(trunc(joined), 'MM-YYYY')

关于如何修改查询的任何建议,可以将结果插入“ JOINED”列为DATETIME类型的新表中?

在此先感谢您的任何提示/建议/评论!


阅读 213

收藏
2021-04-22

共1个答案

小编典典

您可以执行类似的操作to_date('01/'||trunc(joined),'DD/MM/YYYY'),这将首先将其转换为有效日期。您只需要决定使用该月的第一天还是最后一天(最后一天会比较复杂)

另一种选择是使用EXTRACT函数:

 select country, count(*) as members, EXTRACT(MONTH FROM joined) as mn, EXTRACT(YEAR FROM JOINED) as yr,MIN(JOINED) as dt
from table
group by country, EXTRACT(MONTH FROM joined), EXTRACT(YEAR FROM JOINED)

然后从中选择dt列并将其插入

2021-04-22