我看了很多线程,但我找不到任何可以回答我的问题(或者我没有搜索到正确的问题:P)我是自学的mysql,现在我被困在这里,无法找到任何溶液
所以我的问题是,如果可以从两个日期之间的表中选择行,只有那些行之间的差异是例如6个月,如果没有显示已经过了多少时间。
表:
+----+--------+--------------+------------+
| id | name | action | date |
+----+--------+--------------+------------+
| 1 | name 1 | exchange | 2011-06-15 |
| 2 | name 1 | exchange | 2011-12-15 |
| 3 | name 1 | exchange | 2012-06-15 |
| 4 | name 1 | exchange | 2013-01-15 | -1 month
| 5 | name 2 | exchange | 2014-01-15 |
| 6 | name 2 | intervention | 2014-05-15 |
| 7 | name 2 | exchange | 2014-06-15 |
| 8 | name 2 | exchange | 2015-05-15 | - 11 months
+----+--------+--------------+------------+
所以我卡住了
SELECT *
FROM (select * from table
WHERE intervention like '%exchange%'
AND date between '2011-01-15' and NOW() )
WHERE ....
- if difference between row 1 and row 2, row 2 and row 3 till no rows? else write difference ?
但是根据我的猜测,我必须做出2个选择,之后加入他们或类似的东西,1选择将采取所有"一般"行和一个条件介于结果之间我只是不知道我应该如何做到这一点,或者是否只能用sql。
你们有解决方案吗?如果你这样做,你能解释一下你做了什么吗? :d
期望的输出:
+--------+--------------+------------+
| name | action | date |
+--------+--------------+------------+
| name 1 | exchange | 2011-06-15 |
| name 1 | exchange | 2011-12-15 |
| name 1 | OK exchange | 2011-12-15 | - generated because row 1 and 2 meet the requirements
| name 1 | exchange | 2012-06-15 |
| name 1 | OK exchange | 2012-06-15 | - generated because row 2 and 3 meet the requirements
| name 1 | exchange | 2013-01-15 |
| name 1 | 1 month late | 2013-12-15 | - generated because row 3 and 4 DONT meet the requirements
提前谢谢你。 尊重,iaiu
答案 0 :(得分:0)
对我来说,你想要一个混合了源数据和已处理数据的结果,这有点......非正统。让我们从一开始就尝试一下。首先,我们自己加入表格,给他们两个昵称。请注意,t2将每个下一行与t1对配对:
select t1.name as name, t1.date as date, datediff(t2.date, t1.date) as diff_in_days
from table t1, table t2
where
t1.action like '%exchange%' and
t1.date between '2011-01-15' and NOW() and
t1.name = t2.name and
t1.id = t2.id-1
order by t1.name, t1.date;
我们已经得到了它们之间的时差,但是在几天之内。 " 6个月"的定义由你自己决定,让现在假设它是182天。现在让我们在您的业务逻辑中包含上述内容:
select
name,
date,
if(diff_in_days <=182, "OK", concat(diff_in_days - 182, "days late")) as message
from (
select t1.name as name, t1.date as date, datediff(t2.date, t1.date) as diff_in_days
from table t1, table t2
where
t1.action like '%exchange%' and
t1.date between '2011-01-15' and NOW() and
t1.name = t2.name and
t1.id = t2.id-1
) res
order by res.name, res.date;
现在,如果您还需要原始数据,请使用UNION并同时放置上述原始数据表和原始数据表。彼此相邻的行。