简体   繁体   中英

Postgresql Max From Group

Trying to add a flag to the maximum bscmpnstntotal within each objectid. This is compensation data, where objectid represents a specific organization, and bscmpnstntotal equals total compensation for a given employee. I want a flag that specifies who the highest paid person within each organization is:

    WITH "return_skdjrltdorgoffcrtrstkyempl"
AS
(
    SELECT 
        *,
        ROW_NUMBER() OVER (PARTITION BY object_id ORDER BY bscmpnstntotal DESC) AS GroupRank
    FROM ctetable
)
UPDATE "return_skdjrltdorgoffcrtrstkyempl"
SET highestpaidflag2 = CASE WHEN GroupRank = 1 THEN 1 ELSE 0 END;

The error I'm getting is

ERROR: relation "ctetable" does not exist

Table structure: 在此处输入图片说明

Wow, what names.

The problem is that you named the CTE the same as the table (I believe), and the table “shadows” the CTE. You get the error message because the table return_skdjrltdorgoffcrtrstkyempl does not have a column named grouprank .

You'd have to pick a different name for the CTE and join it with the table in the UPDATE statement (using UPDATE ... FROM ):

WITH shortname AS (...)
UPDATE ctetable
SET ...
FROM shortname
WHERE shortname.id = ctetable.id;

My advice, though, would be not to persist that information in the database. Wouldn't the information get invalid if the table data change? Calculate it from the table data whenever you need it.

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