我有一张这样的桌子。
我想得到"成本"根据日期和时间以最快的查询。
例如:
输入:
id_room = 1;
date = 2017/03/24
time from: 05:30:00
time end: 07:30:00
专栏"费用"是指每小时的成本。
如何从timeFrom到timeEnd获得成本金额?
答案 0 :(得分:1)
简而言之:
SELECT SUM((time_to_sec(timediff(LEAST('07:30:00', timeTo), GREATEST('05:30:00', timeFrom))) / 3600) * cost)
FROM `roomcost` r
WHERE WEEKDAY('2017-03-23') BETWEEN dayFrom AND dayTo
AND (timeFrom <= '05:30:00' OR timeTo >= '07:30:00')
AND id_room = 1
我的测试数据:
INSERT INTO `roomcost` (`id`, `id_room`, `dayFrom`, `dayTo`, `timeFrom`, `timeTo`, `cost`) VALUES
(1, 1, 1, 6, '05:00:00', '06:00:00', '50.00'),
(2, 1, 1, 6, '06:00:00', '17:00:00', '100.00'),
(3, 1, 0, 0, '05:00:00', '10:00:00', '200.00');
说明:
WEEKDAY
为您提供给定日期的工作日日期GREATEST
和LEAST
,您可以获得相交的时间范围。timediff
和time_to_sec
SELECT r.*,
GREATEST('05:30:00', timeFrom) AS startTime, LEAST('07:30:00', timeTo) AS endTime
, time_to_sec(timediff(LEAST('07:30:00', timeTo), GREATEST('05:30:00', timeFrom))) / 3600
, (time_to_sec(timediff(LEAST('07:30:00', timeTo), GREATEST('05:30:00', timeFrom))) / 3600) * cost
FROM
{roomcost {1}}