SQL Group By - 计算每月/每年的记录,插入时出错 - 不是有效月份

时间:2012-07-11 18:12:43

标签: sql oracle group-by pivot

我有这个示例数据:

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 - 不是有效月份)

当我将select中的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类型的新表中吗?

提前感谢任何提示/建议/评论!

2 个答案:

答案 0 :(得分:15)

您可以执行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列并插入

答案 1 :(得分:7)

您应该使用trunc功能将日期截断到本月的第一天。这消除了将日期转换为字符串以及将字符串转换回日期的需要。

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