how to change the first day of the week in PostgreSQL

前端 未结 2 1202
闹比i
闹比i 2021-01-25 12:50

I need to change the week start date from Monday to Saturday in PostgreSQL. I have tried SET DATEFIRST 6; but it doesn\'t work in PostgreSQL. Plea

2条回答
  •  广开言路
    2021-01-25 13:43

    It appears that DATEFIRST is a thing in Microsoft Transact-SQL.

    I don't believe Postgres has any exact equivalent, but you should be able to approximate it.

    Postgres supports extracting various parts of a TIMESTAMP via the EXTRACT function. For your purposes, you would want to use either DOW or ISODOW.

    DOW numbers Sunday (0) through Saturday (6), while ISODOW, which adheres to the ISO 8601 standard, numbers Monday (1) through Sunday (7).

    From the Postgres doc:

    This:

    SELECT EXTRACT(DOW FROM TIMESTAMP '2001-02-16 20:38:40');
    

    Returns 5, while this:

    SELECT EXTRACT(ISODOW FROM TIMESTAMP '2001-02-18 20:38:40');
    

    Returns 7.

    So you would use a version of EXTRACT in your queries to get the day of the week number. If you're going to use it in many queries, I would recommend creating a function which would centralize the query in one spot, and return the number transposed as you would like such that it started on Saturday (the transposition would vary depending on which numbering method you used in EXTRACT). Then you could simply call that function in any SELECT and it would return the transposed number.

提交回复
热议问题