I have 10 minutes ie 600 seconds for an activity. I have display the used part and remaining part in minutes. For example if 90 seconds is used then 510 seconds is left. I must display 2 minutes used and 8 minutes left. I have the following SQL
WITH SampleData (SECONDS) AS (
SELECT 90
UNION ALL
SELECT 510
)
SELECT roundedUpSeconds = CEILING(CAST(SECONDS AS DECIMAL(18,6)) / 60)
FROM SampleData
It returns 2 & 9 minutes respectively. It does not sum up to 10. How should I solve this issue so that it sums up to 10. I am using SQL Server.
Getting rounded numbers to add up is tricky. You can calculate the total sum and the cumulative sum -- then use the difference for the last value.
Your data doesn't have an ordering, so this just uses the maximum seconds
as the last score:
WITH SampleData (SECONDS) AS (
SELECT 90
UNION ALL
SELECT 510
)
SELECT (CASE WHEN seconds < max_seconds THEN minutes
ELSE total_minutes - sum(minutes) over (order by seconds rows between unbounded preceding and 1 preceding)
END)
FROM (SELECT sd.*,
(SUM(seconds) OVER ()) / 60 as total_minutes,
CEILING(seconds * 1.0 / 60) as minutes,
MAX(seconds) OVER () as max_seconds
FROM SampleData sd
) sd;
Here is a db<>fiddle.
90 秒是 1.5 分钟,510 秒是 8.5 分钟,加起来是 10,但是由于您使用的是天花板函数,它会将 1.5 取整为 2,将 8.5 取整为 9,因此您没有得到正确的答案
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.