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 请求中描述了周期模型和目标,以查找周期是否被完全覆盖
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';