简体   繁体   English

在Postgresql中选择多个具有别名的列并按别名分组

[英]select multiple columns with alias and group by alias in Postgresql

I'm having a problem with this query. 我对此查询有疑问。 I want to select the ID field and then a date timestamp field has an alias but group by the alias. 我想选择ID字段,然后日期时间戳字段具有别名,但按别名分组。 I can't do it without including the ID field but then then it doesn't keep the uniqueness the group by provides. 如果不包括ID字段,我将无法做到这一点,但是那样就无法保持group by提供的唯一性。 Here is my query which doesn't work. 这是我的查询不起作用。 I get an error about needing to include the ID field. 我收到有关需要包含ID字段的错误。

SELECT id, to_timestamp(start_date)::date as sdate FROM events WHERE end_date > 1349306845 GROUP BY sdate ORDER BY sdate ASC LIMIT 20

UPDATE: After using a function as in below it worked as needed. 更新:使用下面的函数后,它可以根据需要工作。

   SELECT max(id) as id, to_timestamp(start_date)::date as sdate FROM events WHERE end_date > 1349306845 GROUP BY sdate ORDER BY sdate ASC LIMIT 20
SELECT  id, to_timestamp(start_date)::date as sdate 
FROM events
WHERE start_date IN 
   (
     SELECT start_date as sdat 
     FROM events 
     WHERE end_date > 1349306845 
     GROUP BY sdat 
     ORDER BY sdat 
     ASC LIMIT 20 
   )

SELECT  id, to_timestamp(start_date)::date as sdate 
FROM events
WHERE start_date IN 
   (
     SELECT start_date as sdat 
     FROM events 
     WHERE end_date > 1349306845 
     GROUP BY sdat 
   )
ORDER BY sdate 
ASC LIMIT 20 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM