Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
215 views
in Technique[技术] by (71.8m points)

sql - postgres - select one specfic row of another table and store it as column

I have a table for timeTracks with the properties startTime and stopTime that are recorded for another table called project.

With the following aggregates I managed to display the count and sum of the amount of tracks that belongs to a project. In case an active Track (one without stopTime) exists, I want 2 additional columns named "activeTrackId" and "activeTrackStartTime".

SLECT
count(time_track."timeTrackId") AS "timeTracksTotalCount",
floor(date_part('epoch'::text, sum(time_track."stopTime" - time_track."startTime")))::integer AS "timeTracksTotalDurationInSeconds"
activeTimeTrackId ??
activeTimeTrackStartTime ??
...
FROM project
LEFT JOIN time_track on time_track."fkProjectId" = project."projectId"

Technically there can be only one active track at a time. However just in case, it should only select the latest active track, if there a two tracks without stopTime.

How can I that in postgres?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use aggregation functions:

SELECT count(t."timeTrackId") AS "timeTracksTotalCount",
       floor(date_part('epoch'::text, sum(t."stopTime" - t."startTime")))::integer AS "timeTracksTotalDurationInSeconds"
       (array_agg(t."timeTrackId" order by t."startTime" desc) filter (where t."stopTime" is null))[1] as activeTimeTrackId,
       max(t."startTime") filter (where t."stopTime" is null) as activeTimeTrackStartTime 
...
FROM project p LEFT JOIN
     time_track t
     ON t."fkProjectId" = p."projectId"
GROUP BY ?;

Note that Postgres doesn't offer a first() aggregation function, so this uses array aggregation and then takes the first element.

If you are using an older version of Postgres, filter may not be available. You can replace that with case expressions.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...