2017-01-15 65 views
0

我有如下表所示的两个表,我想列出在任务表中使用的位置行基,并且不重复location.id,也按任务表中的列排序。左连接和分组由

我不知道如何解决它使用组或其他方法?
(我之前也查过截然不同,但是它限制选择专栏,好像不是我想要的..)
怎么解决?

location 
id | status | ... 
1 | ... 
2 | ... 

id SERIAL NOT NULL 

task 
id | location_id | create_date | start_date | ... 
1 | 1   | ... 
2 | 1   | ... 
3 | 2   | ... 

id SERIAL NOT NULL 
location_id integer DEFAULT NULL 
create_date timestamp without time zone NOT NULL 
start_date date NOT NULL 

需要输出结果

location order by task.create_date 
id | ... 
1 | ... 
2 | ... 

查询

我加选择t.location_id它的工作原理来算,但我仍然有问题,在选择行

计数工作

SELECT count(l.*) 
    AS total_row_count 
    FROM location l 
     LEFT JOIN (
      SELECT t.location_id 
      FROM task t 
      GROUP BY t.location_id 
      ) t ON t.location_id = l.id 
     WHERE l.status = ANY($1::int[]) 

选择

SELECT 
    l.* 
    FROM location l 
     LEFT JOIN (
      SELECT t.location_id, t.create_date 
      FROM task t 
      GROUP BY t.location_id 
     ) t ON t.location_id = l.id 
     WHERE l.status = ANY($1::int[]) 
     ORDER BY t.create_date desc NULLS LAST, 
     l.name asc NULLS LAST, l.id desc NULLS LAST OFFSET $2 LIMIT $3 

错误:

column "t.create_date" must appear in the GROUP BY clause or be used in an aggregate function SELECT t.create_date, t.location_id

+0

我不明白你想要得到什么结果。将它显示为一张表格,就像您对样本数据所做的一样。 –

+0

请参阅我的更新,我想获取位置表但不重复位置行 – user1775888

+1

您的示例数据不完整。你能否在相关栏目中提供数据? – GurV

回答

1

你可以简单地做一个左连接来获得行的任务表这样的LOCATION_ID和相应的编号:

select l.id, count(t.location_id) times 
from location l 
left join task t 
on l.id = t.location_id 
group by l.id 
order by max(t.create_date) desc; 

如果LOCATION_ID是您的位置表中的唯一(可能是PK),并且您希望从该表中选择全部或多个列,则可以将它们同时置于查询的select和group by子句中。

+0

感谢您的回复,我的问题是如何获取行? t.create并不是独一无二的如何在群组中使用?但我需要按顺序使用它 – user1775888

+0

由于您正在聚合location_id,因此您需要按日期汇总进行排序(可能是我在更新后的答案中使用的最大值或最小值)。 – GurV

+0

select l.location_id ??或者选择l.id?由l.location_id分组?或l.id或t.location_id? – user1775888

1

如果要列出记录和表location列只有这样,你可以使用exists,如下图所示:

select * from location l where exists (select 1 from task where location_id=l.id) 

你可以找到一个演示here

+0

谢谢你的回复,但我也想按任务表 – user1775888

+0

列确定,好吧,你从来没有提到任何关于排序你的问题。如何做*你想订购你的数据呢?您应该 - 如果可能的话 - 相应地编辑您的原始帖子。 – cars10m

+0

请参阅我的更新 – user1775888