SQL:分组依据、按时间排序和以正确格式显示时间

SQL:分组依据、按时间排序和以正确格式显示时间,sql,postgresql,Sql,Postgresql,我是SQL新手,需要按时间排序和分组。同时,我需要以正确的时间格式显示 select test, total from ( select to_char(last_create_date, 'YYYYmm') as "test", count (seq) as "total" from public.newsfeed group by to_char(last_create_date, 'YYYYmm') order

我是SQL新手,需要按时间排序和分组。同时,我需要以正确的时间格式显示

select test, total 
  from (
        select to_char(last_create_date, 'YYYYmm') as "test", count (seq) as "total"
          from public.newsfeed 
         group by to_char(last_create_date, 'YYYYmm')
         order by to_char(last_create_date, 'YYYYmm')) as T1

但是,每当我想以
“MON-YYYY”
格式获取输出时,就会出现以下错误。我怎样才能超越?我已经阅读了stackoverflow中类似的问题,他们建议使用子查询或转换。但我不知道如何将这些应用到我的案例中


请使用
'Mon-YYYY'
格式在下面进行尝试

select to_char(last_create_date, 'Mon YYYY') as "test", count (seq) as total
FROM public.newsfeed 
group by to_char(last_create_date, 'Mon YYYY')
order by to_char(last_create_date, 'Mon YYYY')

试试下面的无需子查询

    select to_char(last_create_date, 'MON YYYY') as "test",
    count(seq) as "total"
    FROM public.newsfeed 
    group by to_char(last_create_date, 'MON YYYY')
    order by to_char(last_create_date, 'MON YYYY')

由于错误消息,您需要在
分组依据
列表中包括非聚合列,如
选择
列表中所示:

select t1.test, t1.total 
  from   
  (select to_char(last_create_date, 'MON YYYY') as test, count (seq) as "total"
     from public.newsfeed 
    group by to_char(last_create_date, 'MON YYYY')
    order by test 
  ) as t1;
但是您不需要将
ORDER BY
子句的确切格式改为
to_char(last_create_date,'MON YYYY')
,您可以使用缩写别名(
test

顺便说一下,您可以用
count(0)
count(1)
count(*)
甚至
count(test)
等替换count(seq)。只要不应用distinct(如
count(distinct测试)


Postgres允许您在
选择中使用列别名。所以,你可以这样写:

select to_char(last_create_date, 'YYYYmm') as test,
       count(seq) as total
from public.newsfeed 
group by test
order by min(last_create_date);
请注意,按
last\u create\u date
的最小值排序将结果按时间顺序排列,而不是按
test
的字母顺序排列

这样可以轻松更改格式:

select to_char(last_create_date, 'Mon YYYY') as test,
       count(seq) as total
from public.newsfeed 
group by test
order by min(last_create_date);

@Danieherrera是的,但他要求
输出为“MON-YYYY”
select to_char(last_create_date, 'Mon YYYY') as test,
       count(seq) as total
from public.newsfeed 
group by test
order by min(last_create_date);