使用EXTRACT函数从时间戳获取年或月时出错

时间:2018-07-03 19:46:16

标签: sql postgresql

我正在运行一个查询,该查询将按Month返回新用户,即按Phone Number,按monthyear分组的首次交易计数。 / p>

这是我的查询:

select extract(year from timestamp FirstOrderDate) as yr, 
       extract(month from timestamp FirstOrderDate) as mon,
       count(*)
FROM (
   SELECT /*The column referred to below is character varying(50) - it is unfortunately not data type date*/
          TO_DATE(MIN("Date_Transaction_Occured"),'mm-dd-yyyy') AS FirstOrderDate
   FROM "TABLE1"
   group by "PhoneNumber"
) AS FirstOrderTable;
group by extract(year from date FirstOrderDate), 
extract(month from date FirstOrderDate);

这是错误:

ERROR:  syntax error at or near "FirstOrderDate"
LINE 1: ...AS total FROM (select extract(year from timestamp FirstOrder...

              ^

1 个答案:

答案 0 :(得分:1)

删除timestamp关键字-仅在指定常量值时才需要,而在引用日期或时间戳类型的列时则不需要:

select extract(year from FirstOrderDate) as yr, 
       extract(month from FirstOrderDate) as mon,
       count(*)
FROM ...
group by extract(year from FirstOrderDate), 
         extract(month from FirstOrderDate);