Oracle SQL中带小数秒的Timestamp求和方案咨询
Hey there! Let's work through this issue you're having with summing those race lap times stored as 6-decimal-second Timestamps. The core problem here is that Timestamp is designed to represent a point in time, not a duration—so directly summing them often leads to truncated precision because most SQL engines don't handle Timestamp sums with full microsecond accuracy by default. Here are your best fixes:
1. Convert Timestamps to Intervals Before Summing (Recommended for Most Databases)
Since your lap times are anchored to '0001-01-01', you can subtract this base timestamp to get an INTERVAL (a duration type), which preserves full microsecond precision when summed.
Example (PostgreSQL):
SELECT SUM(lap_time - '0001-01-01'::TIMESTAMP) AS total_lap_duration FROM race_laps;
This query will return an interval like 00:15:42.123456—complete with all 6 decimal places of your original lap times.
Example (MySQL 8.0+):
MySQL supports interval arithmetic too, though syntax is slightly different:
SELECT SUM(TIMEDIFF(lap_time, '0001-01-01 00:00:00.000000')) AS total_lap_duration FROM race_laps;
The result will retain microsecond precision as long as your table's Timestamp column is defined with (6) precision (e.g., TIMESTAMP(6)).
2. Convert to Microsecond Values for Summing (For Older/Limited SQL Engines)
If your database doesn't support interval summation, convert each Timestamp to a numeric value representing total microseconds since the base time, sum those numbers, then convert back to a readable duration.
Example (MySQL):
-- Calculate total lap time with full microsecond precision SELECT SEC_TO_TIME(SUM(TIMESTAMPDIFF(MICROSECOND, '0001-01-01 00:00:00.000000', lap_time)) / 1000000) AS total_lap_time FROM race_laps;
This converts each lap time to microseconds, sums them, then divides by 1,000,000 to get total seconds, which SEC_TO_TIME formats into a time string with microseconds.
Do You Need to Change Data Types?
Short answer: No, but you might want to for better semantics.
- If you're stuck with your existing Timestamp column, the conversion methods above will fully preserve microsecond precision during sums.
- That said, using an
INTERVALtype (if your database supports it, like PostgreSQL, Oracle, or MySQL 8.0+) is more logical for storing durations like lap times. It eliminates the need for constant base-timestamp conversions and makes queries more readable.
Just double-check that your Timestamp column is explicitly defined with 6-digit precision (e.g., TIMESTAMP(6) in MySQL/PostgreSQL) to ensure microseconds are stored correctly in the first place!
内容的提问来源于stack exchange,提问作者Sławek

