我是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中非常类似的问题,他们建议使用子查询或转换。但是我不知道如何将这些应用于我的案子。
ERROR: column "newsfeed.last_create_date" must appear in the GROUP BY
clause or be used in an aggregate function LINE 1: select test, total
from (select to_char(last_create_date, 'M...
^
********** Error **********
ERROR: column "newsfeed.last_create_date" must appear in the GROUP BY
clause or be used in an aggregate function SQL state: 42803 Character:
41
答案 0 :(得分:1)
Postgres允许您在select
中使用列别名。因此,您可以将其编写为:
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_create_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);
答案 1 :(得分:0)
尝试使用'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')
答案 2 :(得分:0)
尝试如下,无需子查询
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')
答案 3 :(得分:0)
错误消息指出,您需要在GROUP BY
列表中包括未汇总的列,如SELECT
列表中所示:
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)。只要您不应用诸如count(distinct test)