[英]Group By day on PostgreSQL depending on country time zone
I want to group by day counting registers of "ORDERS" table, but I have registers of different timezones because of the countrys.我想按天对“ORDERS”表的计数寄存器进行分组,但是由于国家/地区的原因,我有不同时区的寄存器。
with "end_datetime" as (
select
current_timestamp as "end_date"
), "start_datetime" as (
select case
when date_trunc('weeks', (select "end_date" from "end_datetime") - '8 weeks'::interval) < '2022-01-01 00:00:00'
then '2022-01-01 00:00:00'
else date_trunc('weeks', (select "end_date" from "end_datetime") - '8 weeks'::interval)
end as "initial_date"
),"principal" as (
select DATE_TRUNC('day',o."createdAt")::TIMESTAMP::DATE ,
COUNT(o.id) AS "countTotal",
lower(countries."name") as "country",
(select "initial_date" from "start_datetime") as initial_date,
(select "end_date" from "end_datetime" as end_date)
from "Orders" as o
left join "Cities" as "cities" on "cities"."id" = o."cityID"
left join "Countries" as "countries" on "countries"."id" = "cities"."countryID"
left join "Enterprises" as "enterprises" on "enterprises".id = o."enterpriseID"
left join "GeneralTypes" as "generaltypes" on "generaltypes".subtype = o."statusID"
where o."createdAt" between (select "initial_date" from "start_datetime") and (select "end_date" from "end_datetime") --Info de las últimas 8 semanas
GROUP BY DATE_TRUNC('day',o."createdAt"), "country"
)select * from "principal"
Is there a good way to do that?有什么好的方法吗?
The field o."createdAt" is timestamptz字段o."createdAt"是timestamptz
You will need a table mapping country to timezone name.您将需要一个将国家/地区映射到时区名称的表。 Your problem is that many countries have multiple timezones so you will presumably have to pick one city in each country to base your timezone off.
您的问题是许多国家/地区有多个时区,因此您可能必须在每个国家/地区选择一个城市来确定您的时区。
Then you can do AT TIME ZONE
like this:然后你可以像这样在
AT TIME ZONE
做:
=> SELECT tz, CURRENT_TIMESTAMP AT TIME ZONE tz FROM (VALUES ('Europe/Paris'), ('Europe/Moscow')) t (tz);
tz │ timezone
───────────────┼───────────────────────────
Europe/Paris │ 2022-02-02 18:29:47.56131
Europe/Moscow │ 2022-02-02 20:29:47.56131
(2 rows)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.