【发布时间】:2017-05-30 05:55:42
【问题描述】:
我有如下两个表,我想根据在任务表中使用的位置行列出,并且不要重复 location.id,也在任务表中按列排序。
我不确定如何使用 group by 或其他方法解决它?
(我之前也检查过 distinct,但它限制选择特定列,似乎不是我想要的..)
如何解决?
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 | ...
查询
我添加了 select 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
错误:
列“t.create_date”必须出现在 GROUP BY 子句中或被使用 在聚合函数中 SELECT t.create_date, t.location_id
【问题讨论】:
-
我不明白你想要得到什么结果。将其显示为表格,就像您对示例数据所做的那样。
-
请看我的更新,我想获取位置表但不重复位置行
-
您的样本数据不完整。您能否提供相关列中的数据?
-
@user1775888 样本输出可以通过
select * from location获取。显然你没有提供一个实质性的例子。如果您需要帮助,您需要展示您正在努力实现的目标。
标签: sql postgresql group-by left-join