0

我有一个名为Logs

 ->OCCUR_TIME --date and time
 ->NAME --name of a person
 ->KIND --the kind of log (eg. 40 means `something`)
 ->VALUE --the value of the kind of log (eg. 99)

我必须创建一个查询:

SELECT 
*
FROM        LOGS
WHERE       NAME='dude'
ORDER BY    KIND, OCCUR_TIME, VALUE;

现在这会显示日志并按种类排序,然后是发生时间(如果发生时间完全相同,它将按值排序)。

笔记:

  • KIND 的 VALUE 必须始终为 +1
  • 如果不报告问题。

例如,如果日志出现问题并且在 VALUE 400 之后下一个 VALUE 是 398,该怎么办?

例子:

   Occur_Time                | Name    | Kind | Value
   2012-06-26 15:14:25.407     dude      40     398
   2012-06-27 16:55:28.730     dude      40     399
   2012-06-30 02:43:26.763     dude      40     400
   2012-06-30 05:26:32.673     dude      40     398 <-- data prob. (possible rollback)
   2012-06-30 16:35:28.330     dude      40     399 <-- problem continuing
   2012-06-20 20:29:51.207     dude      41     100 <-- no prob. bcoz its another kind
   2012-06-23 05:50:59.130     guy       40     500 <-- no prob. bcoz its another name

我想要一个能找到问题的查询,以及它从哪里开始。像这样?

请帮忙。谢谢你。

4

2 回答 2

1

不是一个理想的查询,但这将列出问题:

select l1.*, l2.* 
from logs l1 -- self join on the columns that are the same
  inner join logs l2 on l1.Name = l2.Name and l1.Kind = l2.kind
where l1.occur_time > l2.occur_time
  and l1.value < l2.value

基本上这会发现所有不匹配的地方,时间会增长,但价值会减少。但是,每次出现它都会返回很多重复项,因此您可能必须使用以下内容进行限制:

select distinct l1.Name, l1.Kind
from logs l1 -- self join on the columns that are the same
  inner join logs l2 on l1.Name = l2.Name and l1.Kind = l2.kind
where l1.occur_time > l2.occur_time
  and l1.value < l2.value

隔离有问题的名称/种类对

于 2012-07-25T13:39:28.557 回答
0

在 SQL Server 2012 中,您可以使用 lag() 函数来执行此操作。

我假设您使用的是早期版本,但在 2005 年之后。您可以使用嵌套的 windows 函数来执行此操作。

select name, KIND, OCCUR_TIME, VALUE,
       (case when max(testval) over (partition by kind, name) <> min(testval) over (partition by kind)
              then 'FAIL'
              else 'OKAY'
        end) as status
from (SELECT *,
             row_number() over (partition by kind, name order by occur_time, value) as seqnum,
             (value - row_number() over (partition by kind, name order by occur_time, value)) as testval
      FROM LOGS
      WHERE NAME='dude'
     ) t
  ORDER BY name, KIND, OCCUR_TIME, VALUE

这个想法是使用 row_number() 来生成一个数字序列。值和序列之间的差异应该是一个常数。外部查询查看这些的最小值和最大值。如果它们不同,那么您就有问题了。

于 2012-07-25T13:44:33.320 回答