Home >Database >Mysql Tutorial >How to Sum Time Values (HH:mm Format) in SQL?

How to Sum Time Values (HH:mm Format) in SQL?

Barbara Streisand
Barbara StreisandOriginal
2025-01-04 15:10:40268browse

How to Sum Time Values (HH:mm Format) in SQL?

Calculating the Sum of Time Values using SQL

In SQL, you can calculate the sum of time values, such as those in your "timeSpent" column with an HH:mm format, using the following query:

SELECT SEC_TO_TIME( SUM(TIME_TO_SEC(`timeSpent`)) ) AS timeSum
FROM YourTableName

Here's how this query works:

  • TIME_TO_SEC(timeSpent): Converts each value in the "timeSpent" column from a time format to seconds.
  • SUM(TIME_TO_SEC(timeSpent)): Calculates the sum of the converted seconds.
  • SEC_TO_TIME: Converts the summed seconds back into a time format.

Example Usage:

Suppose your "YourTableName" has the following data:

TimeFrom | TimeUntil | Time spent
---------------------------------
10:00:00 | 12:00:00 | 02:00:00
12:00:00 | 09:15:00 | 01:15:00

Running the above query would give you the following result:

timeSum
--------
03:15:00

This represents the total sum of time spent in the "timeSpent" column, calculated as 2 hours, 15 minutes.

The above is the detailed content of How to Sum Time Values (HH:mm Format) in SQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn