简体   繁体   中英

Select all columns grouping by version - Postgres

I need to query all columns in a table of all customers, the main factor being the latest version for each customer.

My table:

在此处输入图像描述

My Query:

SELECT DISTINCT ON(code)
    code,
    namefile,
    versioncol,
    status
FROM table_A
    ORDER BY versioncol desc

Error:

ERROR: SELECT DISTINCT ON expressions must match initial ORDER BY expressions LINE 1: SELECT DISTINCT ON(code)

Postgres' error message is trying to tell you what to do:

DISTINCT ON expressions must match initial ORDER BY expressions

Actually that's quite clear: to make your code a valid DISTINCT ON query, you just need to add code (that's the DISTINCT ON expression ) as a first sorting criteria to the query (ie as initial ORDER BY ).

SELECT DISTINCT ON(code) a.*
FROM table_A a
ORDER BY code, versioncol DESC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM