SET @start = '2013-05-14';
SET @end = '2013-11-01';
SET @days = DATEDIFF(@end, @start);
SET @UnusedDays = 0;
SELECT @UnusedDays := DATEDIFF(end_at,@end) FROM PERIODS WHERE (@end > start_at AND @end <= end_at);
SELECT @UnusedDays := @UnusedDays + DATEDIFF(@start, start_at) FROM PERIODS WHERE (@start >= start_at AND @start < end_at);
SELECT @days + @UnusedDays - SUM(DATEDIFF(end_at, start_at)) AS Shortfall
FROM PERIODS
WHERE (@start >= start_at AND @start < end_at)
OR (end_at < @end AND start_at > @start)
OR (@end > start_at AND @end <= end_at);
使用它作为原始SQL的解决方案也会受到欢迎,因为到目前为止我无法运行它。
更新:期间模型和目标在SQL request to find if a period is fully covered
中描述UPDATE2:如果我尝试使用原始的SQL查询,如:
query = %Q[
SET @start = '2013-05-14';
SET @end = '2013-11-01';
SET @days = DATEDIFF(@end, @start);
SET @UnusedDays = 0;
SELECT @UnusedDays := DATEDIFF(end_at,@end) FROM PERIODS WHERE (@end > start_at AND @end <= end_at);
SELECT @UnusedDays := @UnusedDays + DATEDIFF(@start, start_at) FROM PERIODS WHERE (@start >= start_at AND @start < end_at);
SELECT @days + @UnusedDays - SUM(DATEDIFF(end_at, start_at)) AS Shortfall
FROM PERIODS
WHERE (@start >= start_at AND @start < end_at)
OR (end_at < @end AND start_at > @start)
OR (@end > start_at AND @end <= end_at);
]
Period.connection.select_all(query).first.map{|k,v| v }.first == 0
我收到以下错误:
ActiveRecord::StatementInvalid:
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SET @end = '2013-11-01';