进行比较时,一种方法是将要比较的记录放在同一行中。由于您要比较从“当前到第二天”的记录,您可以将表本身连接起来,日期相差一天。这是通过DATEDIFF
计算两个日期之间不同天数的函数来完成的。
查询 1:
select
today.*,
followingday.date as ndate, followingday.gr1 as ngr1,
followingday.gr2 as ngr2, followingday.gr3 as ngr3
from mytable today
join mytable followingday on DATEDIFF(followingday.date, today.date) = 1
这将给出以下结果,将连续一天的值与前一天结合起来(我已将列重命名为followingday
前缀为,n
以便所有列都具有唯一的名称,否则它们不会全部显示在结果集中):
结果(演示):
| DATE | GR1 | GR2 | GR3 | NDATE | NGR1 | NGR2 | NGR3 |
------------------------------------------------------------------------------------------------------------
| November, 30 2011 00:00:00+0000 | c | a | f | December, 01 2011 00:00:00+0000 | b | d | c |
| November, 29 2011 00:00:00+0000 | a | b | f | November, 30 2011 00:00:00+0000 | c | a | f |
| November, 28 2011 00:00:00+0000 | f | b | c | November, 29 2011 00:00:00+0000 | a | b | f |
| November, 27 2011 00:00:00+0000 | a | c | d | November, 28 2011 00:00:00+0000 | f | b | c |
| November, 26 2011 00:00:00+0000 | c | a | b | November, 27 2011 00:00:00+0000 | a | c | d |
现在结果被组合成一行,我们可以对数据应用一些逻辑。在这种情况下,规则是“任何列的值在第二天都有一个'a',后跟一个'f'等级,无论哪个列有等级。” 因此,任何一个成绩都是a
当天的成绩,然后任何成绩都是第二天的成绩f
:
查询 2:
...
where (today.gr1 = 'a' or today.gr2 = 'a' or today.gr3 = 'a')
and (followingday.gr1 = 'f' or followingday.gr2 = 'f' or
followingday.gr3 = 'f')
结果(演示):
| DATE | GR1 | GR2 | GR3 | NDATE | NGR1 | NGR2 | NGR3 |
------------------------------------------------------------------------------------------------------------
| November, 29 2011 00:00:00+0000 | a | b | f | November, 30 2011 00:00:00+0000 | c | a | f |
| November, 27 2011 00:00:00+0000 | a | c | d | November, 28 2011 00:00:00+0000 | f | b | c |
结果显示,有一个等级a
,11-27-11
其次是一个等级f
。11-28-11
同样,有一个等级a
on 11-29-11
,然后是一个等级f
on 11-30-11
。这些应该是满足规则的唯一结果。