简体   繁体   中英

Order a postgreSQL query on a rolling period (2)

this is my query :

SELECT 
    type.name_type as type_name,
    extract(day from event.creation_date) as days,
    count(0) as number
FROM event, type, event_type
WHERE event.id = event_type.event_id
    AND type.type_id = event_type.type_id
AND event.creation_date between now() - interval '1 YEAR' and now()
GROUP BY days, type_name
order by min(event.creation_date) asc;

my issue is that when i visualize its result, there are several rows having the same day number. i would like days' numbers to act like a key so that each day number has a unique row.

the other requirement is that the result has to be ordered according to the rolling month (based on the current date), so here for example the first row is the 7 and the last row the 6.

and ideas ?

any help is appreciated :) have a nice day !

(PS : i can't provide sample data)

I'm responding to Armand's comment that ' my real struggle is to have it ordered as i wish '

The problem is really, "How can I order a sequence of numbers as 7, 6, 5, 4, 3, 2, 1, 31, 30, 29, etc.?"

The answer is to use modular arithmetic. If you add 30 minus day(current_date) to each of these numbers you get 30, 29, 28, 27, 26, 25, 24, 54, 53, 52, etc.

If you then take the remainder (modulus) of these numbers divided by 31, you get 30, 29, 28, 27, 26, 25, 24, 23, 22, 21. and voilà, you have a sequence to put in an Order By (descending).

So the answer is Order By mod(days + 30 - day(Current_date),31) desc

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