2

我有一张桌子,有 4columns(date,gr1,gr2,gr3)(gr),等级从(a 到 f)不等。

date        gr1 gr2 gr3
2012-1-1    a   b   c
2011-11-31  b   d   c
2011-11-30  c   a   f
2011-11-29  a   b   f
2011-11-28  f   b   c
2011-11-27  a   c   d
2011-11-26  c   a   b

我需要查询以下内容:我需要选择任何列值在第二天有一个“a”后跟一个“f”等级,无论哪些列有等级。

我是新手,任何帮助将不胜感激......祝大家新年快乐!

4

1 回答 1

1

进行比较时,一种方法是将要比较的记录放在同一行中。由于您要比较从“当前到第二天”的记录,您可以将表本身连接起来,日期相差一天。这是通过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 |

结果显示,有一个等级a11-27-11其次是一个等级f11-28-11同样,有一个等级aon 11-29-11,然后是一个等级fon 11-30-11。这些应该是满足规则的唯一结果。

于 2012-12-31T18:36:55.967 回答