我搜索了上述主题,并且只在Oracle中获取查询,该查询使用特定于oracle的特定关键字。
+----------+------------+--------------------+
| Agent_id | valid_from | last_modified_date |
+----------+------------+--------------------+
| 13002 | 2010-12-25 | 2011-01-03 |
| 13002 | 2011-01-03 | 2011-08-25 |
| 13002 | 2011-08-26 | 2012-12-30 |
| 13002 | 2013-01-01 | 2013-01-01 |
| 12110 | 2014-02-27 | 2014-03-03 |
| 12110 | 2014-03-25 | 2014-12-25 |
+----------+------------+--------------------+
我有上面的表值,想要检索第一行的last_modified_date
和第二行的valid_from
日期之间的差异,同样对于同一个代理(此处为agent id
)。
结果表:
+----------+------------+--------------------+-----------+
| Agent_id | valid_from | last_modified_date | datediff |
+----------+------------+--------------------+-----------+
| 13002 | 2010-12-25 | 2011-01-03 | 0 |
| 13002 | 2011-01-03 | 2011-08-25 | 0 |
| 13002 | 2011-08-26 | 2012-12-30 | 1 |
| 13002 | 2013-01-01 | 2013-01-01 | 1 |
| 12110 | 2014-02-27 | 2014-03-03 | 0 |
| 12110 | 2014-03-25 | 2014-12-25 | 22 |
+----------+------------+--------------------+-----------+
如果第一行没有比较日期,则差异应为0
。
这些是日期,其中状态从Y更改为D,并在代理没有任何活动时查找。
请帮助!!
答案 0 :(得分:1)
使用DATEDIFF
功能。
MySQL 的示例:
SELECT
DATEDIFF(valid_from,last_modified_date) AS 'days'
FROM
table
这将返回天数差异。 Source
SQL Server 2005-2012 :
SELECT
DATEDIFF(day,valid_from,last_modified_date ) AS 'days'
FROM
table
这将返回天数差异。 Source
答案 1 :(得分:0)
天数差异。
SELECT *,MIN(COALESCE(DATEDIFF(t1.valid_from, t2.last_modified_date),0))
FROM agents t1
LEFT JOIN agents t2 ON t1.agent_id=t2.agent_id AND t1.valid_from >= t2.last_modified_date
GROUP BY t1.agent_id, t1.valid_from
答案 2 :(得分:0)
在MySQL中执行此操作的最简单方法是使用变量:
select t.*
from (select t.*,
if(agent_id = @agent_id, datediff(valid_from, @last_modified_date), 0) as datediff,
@last_modified_date := last_modified_date,
@agent_id := agent_id
from table t cross join
(select @agent_id := 0, @last_modified_date := 0) const
order by agent_id, valid_from
) t;
您还可以使用相关子查询计算上一个日期。
顺便说一句,您在Oracle中使用的那些关键字不是特定于Oracle的。它们是MySQL不支持的ANSI标准功能。
答案 3 :(得分:0)
尝试此查询。相应地更改order by子句。
我根据您的结果假设了订单。
select agent_id,
max(valid_from) as valid_from,max(last_modified_date) as last_modified_date,
ifnull(datediff(max(valid_from),max(last_modified_date)),0)as difference
from
(
select @a:=@a+1,
case when (@a+1)%2 = 0 then @b:=@a-2 else @b end as b , agent_id,
case when @a%2=0 then valid_from else 0 end as valid_from,
case when @a%2<>0 then last_modified_date else 0 end as last_modified_date
from table a ,(select @a:=0,@b:=0) b
order by agent_id desc ,valid_from
) a
group by agent_id,b
答案 4 :(得分:0)
只需改变结果中的字段顺序
mysqli_multi_query('
set @i='';
select
Agent_id, if(@i='', 0,datediff(valid_from,@i)) as datediff, valid_from, (@i:=last_modified_date) as last_modified_date
from
your_table'
);