postgresql:从包含多行的结果中只获取一条记录

时间:2018-06-18 06:08:56

标签: sql postgresql

我已经编写了一个查询,其中列出了已应用于其的所有任务。我所写的查询,如果相同的任务正在应用不同的工作,即使是已列出。

例如,如果task1有3种不同的应用,即2.5,6,3小时,则会列出这些。我试图仅列出第一个条目,只列出task1有2.5小时的条目。

以下是我编写的查询,其中列出了连接到不同表格的所有任务:

 SELECT t.taskid AS id,
    t.projectid AS project,
    te.effort AS effort,
    (((t.taskname::text || ' | '::text) || m.milestonename::text) || ' | '::text) || p.projectname::text AS name,
    t.status,
    1 AS version
   FROM task t
     LEFT JOIN timeentry te ON t.taskid = te.taskid
     LEFT JOIN project p ON t.projectid = p.projectid
     LEFT JOIN milestonetask tm ON t.taskid = tm.taskid
     FULL JOIN milestone m ON tm.milestoneid = m.milestoneid
  WHERE m.milestoneid IS NOT NULL
UNION
 SELECT distinct(t.taskid) AS id,
    t.projectid AS project,
    te.effort AS effort,
    (t.taskname::text || ' | (--no milestone--) | '::text) || p.projectname::text AS name,
    t.status,
    1 AS version
  FROM task t 
     LEFT JOIN timeentry te ON t.taskid = te.taskid
     LEFT JOIN project p ON t.projectid = p.projectid
     LEFT JOIN milestonetask tm ON t.taskid = tm.taskid
     FULL JOIN milestone m ON tm.milestoneid = m.milestoneid
  WHERE NOT (tm.taskid IN ( SELECT DISTINCT milestonetask.taskid
           FROM milestonetask
          WHERE milestonetask.milestoneid IS NOT NULL));

这是我现在得到的结果:

id | project | effort |        name       | status | version 
----+---------+--------+------------------+--------+---------
 89 |       1 |      5 | Coding for clock | Active |       1
 89 |       1 |      2 | Coding for clock | Active |       1
 89 |       1 |      4 | Coding for clock | Active |       1

对于同一任务而不是这些多行,我试图只为taskid 89设置一行,只要它已经付出了努力。

如果我已经足够清楚,请告诉我,非常感谢您的帮助,并提前致谢。

2 个答案:

答案 0 :(得分:1)

在Postgres中,您可以使用distinct on

with t as (
      <your query here>
     )
select distinct on (id) t.*
from t
order by id;

答案 1 :(得分:0)

如何将整个查询包装到

SELECT DISTINCT(id), * FROM (
<your query>
) subquery;