我有这个查询(对于Oracle):
SELECT TO_DATE(TO_CHAR(CREATIONDATE, 'MM.YYYY'), 'MM.YYYY') as month,
SUM(count(*)) over (order by to_date(TO_CHAR(CREATIONDATE, 'MM.YYYY'),'MM.YYYY') ) as total
FROM person
GROUP BY TO_DATE(TO_CHAR(CREATIONDATE, 'MM.YYYY'), 'MM.YYYY')
按月计算人数,按正确顺序计算:
实施例。 01.2014,02.2014,...,01.2015。 02.2015,......
它正在运作但是:
答案 0 :(得分:1)
to_date(TO_CHAR(CREATIONDATE, 'MM.YYYY'),'MM.YYYY')
和Analytic window
表达式中不需要Group by
部分。而且,为什么在select中再次将文字转换为日期?您只需使用TO_CHAR
来显示所需的格式。
检查一下:
SQL> WITH DATA AS
2 ( SELECT SYSDATE dt FROM dual CONNECT BY LEVEL< 11
3 )
4 SELECT TO_CHAR(dt,'MM.YYYY') dt,
5 SUM(COUNT(*)) over (order by dt ) cnt
6 FROM DATA
7 GROUP BY dt
8 /
DT CNT
------- ----------
10.2014 10
SQL>
答案 1 :(得分:1)
我认为这三个数据库中没有兼容的日期功能。你可以接近这样的东西:
select month(creationdate) as mon, year(creationdate) as yr,
sum(count(*)) over (order by min(creationdate)) as total
from person
group by month(creationdate), year(creationdate);
以上在Oracle和SQL Server中有效。对于Postgres,您可以轻松定义month()
和year()
函数。
您可以使用您的版本或在Postgres和Oracle的上述版本中使用extract(month from creationdate), extract(year from creationdate)
。