简体   繁体   中英

Grouping by “on the fly” calculation in Postgres

Very simple question here, but a quick google search didn't seem to be definitive (and I do not have access to a DB to test right now). I would like to check whether you can do "on the fly" grouping in Postgres (as is possible in SQL Server). best way to clarify is an example ie can I do this to group by weekly periods:

select ...
from ...
group by cast((current_date - transaction_date)/7 as int)

or is it necessary to first define a week column in a subquery (as per the calculation above) and then do the grouping?

Thanks in advance for your help.

You can include most expressions in the GROUP BY , so your code is fine. This is true in Postgres and in almost any database.

It is unusual to have an aggregation query where the aggregation expressions are not part of the GROUP BY . But if you have data on every day, then this is a sensible query:

select min(date_trunc(transaction_date)) as week_start, count(*)
from ...
group by cast((current_date - transaction_date)/7 as int)

You surely can. I would slightly modify your example like

select cast((current_date - transaction_date)/7 as int) as wp, ... 
  from ...
 group by wp;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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