[英]PostgreSQL DISTINCT ON
I am not able to define an alias or to choose specific columns, works only with wildcard:我无法定义别名或选择特定列,仅适用于通配符:
Working:在职的:
SELECT DISTINCT ON (r.InsertDate) *
FROM public.server AS s
LEFT JOIN public.Report AS r ON s.Id = r.ServerId
ORDER BY r.InsertDate DESC;
Not working:不工作:
SELECT DISTINCT ON (r.InsertDate) LastReport, s.Id, s.Servername
FROM public.server AS s
LEFT JOIN public.Report AS r ON s.Id = r.ServerId
ORDER BY r.InsertDate DESC;
Error错误
ERROR: column "lastreport" does not exist
LINE 1: SELECT DISTINCT ON (r.InsertDate) LastReport, s.Id, s.Serve...
^
SQL state: 42703
Character: 36
Also not working:也不工作:
SELECT DISTINCT ON (r.InsertDate) , s.Id, s.Servername
FROM public.server AS s
LEFT JOIN public.Report AS r ON s.Id = r.ServerId
ORDER BY r.InsertDate DESC;
ERROR: column "lastreport" does not exist
LINE 1: SELECT DISTINCT ON (r.InsertDate) LastReport, s.Id, s.Serve...
^
SQL state: 42703
Character: 36
ERROR: syntax error at or near ","
LINE 1: SELECT DISTINCT ON (r.InsertDate) , s.Id, s.Servername
^
SQL state: 42601
Character: 36
Any idea?任何的想法?
You seem to be confused about DISTINCT ON
.您似乎对
DISTINCT ON
感到困惑。 It does not "return a column".它不“返回一列”。 It is a syntactic construct.
它是一个句法结构。 These are variations of the
SELECT
:这些是
SELECT
的变体:
SELECT ALL
SELECT DISTINCT
SELECT DISTINCT ON ()
(The first is the default and never used in practice.) (第一个是默认值,在实践中从未使用过。)
The column list follows these constructs.列列表遵循这些结构。 So, apparently you want:
所以,显然你想要:
SELECT DISTINCT ON (r.InsertDate) r.InsertDate as LastReport, s.Id, s.Servername
FROM public.server s LEFT JOIN
public.Report r
ON s.Id = r.ServerId
ORDER BY r.InsertDate DESC;
It turns out that DISTINCT ON
is actually parsed after the rest of the SELECT
clause, so you can use column aliases:结果发现
DISTINCT ON
其实是在SELECT
子句的rest之后解析的,所以可以使用列别名:
SELECT DISTINCT ON (LastReport) r.InsertDate as LastReport, s.Id, s.Servername
FROM public.server s LEFT JOIN
public.Report r
ON s.Id = r.ServerId
ORDER BY LastReport DESC;
However, the alias must be defined in the column list after the distinct on
.但是,别名必须在
distinct on
之后的列列表中定义。
Note that you are using a LEFT JOIN
, so r.InsertDate
could be NULLL
.请注意,您使用的是
LEFT JOIN
,因此r.InsertDate
可能是NULLL
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.