📅  最后修改于: 2023-12-03 15:03:50.451000             🧑  作者: Mango
In PostgreSQL, the TRUNC function is used to truncate a number to a specified precision. The precision is specified as an integer, which determines the number of decimal places to truncate to. TRUNC returns the integer value and discards the decimal places. In addition to the integer values, TRUNC can also be used with timestamp and interval values.
The basic syntax of the TRUNC function is as follows:
TRUNC(number, precision)
Where:
SELECT TRUNC(123.456, 2);
Output:
123.45
In this example, the number 123.456 is truncated to 2 decimal places.
SELECT TRUNC(456.789, -1);
Output:
450
In this example, the number 456.789 is truncated to the nearest tens place.
SELECT TRUNC(TIMESTAMP '2021-01-01 12:50:30.123456', 'hour');
Output:
2021-01-01 12:00:00
In this example, the timestamp value is truncated to the hour.
SELECT TRUNC(INTERVAL '2 days 12:00:00', 'day');
Output:
2 days
In this example, the interval value is truncated to the day.
The TRUNC function in PostgreSQL is a powerful tool for truncating numeric, timestamp, and interval values to a specified precision. By specifying the precision, you can control the level of detail in the output, and ensure that the values are consistent across your application.