如何在 GROUP BY 和 ORDER BY 中使用多列但只有一列

Posted

技术标签:

【中文标题】如何在 GROUP BY 和 ORDER BY 中使用多列但只有一列【英文标题】:How to use multiple columns but only one column in GROUP BY and ORDER BY 【发布时间】:2020-11-06 03:39:18 【问题描述】:

我想显示连接表中的多列,但只对group byorder by 使用一列

我的 PostgreSQL 查询是这样的:

SELECT DISTINCT ON (r.id_rekrutmen)
       r.id_rekrutmen,
       r.judul_rekrutmen,
       rw.tanggal_rekrutmen
FROM rekrutmen r
   INNER JOIN rekrutmen_waktu rw
      ON r.id_rekrutmen = rw.id_rekrutmen
ORDER BY r.id_rekrutmen, rw.tanggal_rekrutmen DESC;

【问题讨论】:

查询看起来没问题;你有什么问题? 我无法像使用该查询的示例图像那样显示, 你的意思是... ORDER BY r.id_rekrutmen DESC, rw.tanggal_rekrutmen DESC; 吗? 我想要 "ORDER BY tanggal_rekrutmen DESC" 那么如果你这样做ORDER BY rw.tanggal_rekrutmen DESC会有什么问题 【参考方案1】:

我想这就是你想要的:

SELECT 
           r.id_rekrutmen,
           r.judul_rekrutmen,
           MAX(rw.tanggal_rekrutmen) AS tanggal_rekrutmen
    FROM rekrutmen r
       INNER JOIN rekrutmen_waktu rw
          ON r.id_rekrutmen = rw.id_rekrutmen
    GROUP BY 
           r.id_rekrutmen,
           r.judul_rekrutmen,

【讨论】:

非常感谢,和我一起工作,SELECT r.id_rekrutmen, r.judul_rekrutmen, MAX(rw.tanggal_rekrutmen) AS tanggal_rekrutmen FROM rekrutmen r INNER JOIN rekrutmen_waktu rw ON r.id_rekrutmen = rw。 id_rekrutmen GROUP BY r.id_rekrutmen, r.judul_rekrutmen ORDER BY tanggal_rekrutmen DESC

以上是关于如何在 GROUP BY 和 ORDER BY 中使用多列但只有一列的主要内容,如果未能解决你的问题,请参考以下文章

order by 和 group by 的区别?

sql中group by和order by的区别

SQL语句中,如果有group by 和order by两个语句,是先分组还是先排序?

SQL中,group by 跟order by有什么区别?

SQL语句中,如果有group by 和order by两个语句,是先分组还是先排序?

Sql order by 和 group BY 如何共同运用?