开发者

SQL: Column formula

I am trying to create a formula for a cost column which calculates the cost based on the difference between other columns and it is not working.

Parking_Cost is the field to have the cost based on the difference between ParkingStartTime and ParkingEndTime * 5 since 1 hours = $5.00.

Formula:

(CONVERT([int],[ParkingEndTime]-[ParkingStartTime]*开发者_开发问答5,(0)))

I would really appreciate any suggestion?

Regards.


Use DATEDIFF to determine the difference between dates/times. Your formula could be something like this:

DATEDIFF(minute, ParkingStartTime, ParkingEndTime) / 60 * 5

Of course you could use just

DATEDIFF(hour, ParkingStartTime, ParkingEndTime) * 5

which is simpler, but it might give you undesired results in some cases. For example, if the start time was 8:55 and the end time 9:05, DATEDIFF(hour, ...) would return 1 although the actual difference is much less, just 10 minutes. It's because DATEDIFF in essence truncates the times to the units specified and then calculates the difference.

So a similar situation can be with minutes, but at least with minutes you would have better granularity. For example, you would receive the answer of 60 when calculating DATEDIFF(minute, '5:20:57', '6:20:04'), even though it's in fact slightly more than 59 minutes, but the inaccuracy is not so big as can be with DATEDIFF(hour, ...).

If you want to have even better granularity, calculate the difference in seconds and divide by 3600 to get whole hours:

DATEDIFF(second, ParkingStartTime, ParkingEndTime) / 3600 * 5

UPDATE

In SQL Server, when an integer is divided by an integer, the result will be integer too.

If you need the result to be more precise, you can ensure it like this (using the last expression above):

DATEDIFF(second, ParkingStartTime, ParkingEndTime) / 3600.0 * 5
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜