简体   繁体   English

在滚动期间订购 postgreSQL 查询 (2)

[英]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.另一个要求是必须根据滚动月份(基于当前日期)对结果进行排序,因此这里例如第一行是 7,最后一行是 6。

and ideas ?和想法?

any help is appreciated :) have a nice day !任何帮助表示赞赏:) 祝你有美好的一天!

(PS : i can't provide sample data) (PS:我不能提供样本数据)

I'm responding to Armand's comment that ' my real struggle is to have it ordered as i wish '我正在回应 Armand 的评论,即“我真正的挣扎是按照我的意愿订购

The problem is really, "How can I order a sequence of numbers as 7, 6, 5, 4, 3, 2, 1, 31, 30, 29, etc.?"真正的问题是,“我如何将数字序列排序为 7、6、5、4、3、2、1、31、30、29 等?”

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.如果您将30 minus day(current_date)添加到这些数字中的每一个,您将得到30 minus day(current_date)等。

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).如果你然后将这些数字的余数(模数)除以 31,你会得到 30、29、28、27、26、25、24、23、22、21。瞧,你有一个序列来放置一个订单通过(降序)。

So the answer is Order By mod(days + 30 - day(Current_date),31) desc所以答案是Order By mod(days + 30 - day(Current_date),31) desc

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

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