根据其他行标准显示行

时间:2016-12-02 10:45:21

标签: sql-server-2008

我希望在sql表中显示某些行,这些行称为基于后面的行条目的部分。 请参阅下面的列表。我想在后面的行中为每个特定的模型和部分显示没有类0的行。

Log | SourceTime| Class| model | part
----+-----------+------+-------+-----
614 | 14:14     | 0    | FORD  | right wing 
613 | 14:13     | 1    | FORD  | right wing
612 | 14:12     | 1    | TOYOTA| left wing
611 | 14:11     | 0    | TOYOTA| right wing 
610 | 14:10     | 1    | TOYOTA| right wing 
609 | 14:09     | 0    | OPEL  | right lamp
608 | 14:08     | 1    | OPEL  | right lamp
607 | 14:07     | 1    | OPEL  | back right wheel 
606 | 14:06     | 0    | FORD  | right wheel
605 | 14:05     | 1    | FORD  | right wheel

这两行应显示

612 | 14:12     | 1    | TOYOTA| left wing
607 | 14:07     | 1    | OPEL  | back right wheel 

1 个答案:

答案 0 :(得分:1)

试试这个:同一桌面上的多个CTE可以解决您的问题

WITH t1 AS(

         SELECT *,
                ROW_NUMBER() OVER (PARTITION BY LOG ORDER BY LOG) RN
         FROM TableName
),
t2 AS(

         SELECT *,
                ROW_NUMBER() OVER (PARTITION BY LOG ORDER BY LOG) RN
         FROM TableName
)
SELECT t1.*
FROM t1
WHERE Class <>  0 AND
      NOT EXISTS ( SELECT 1 
                   FROM t2 
                   WHERE t1.Model=t2.Model AND 
                         t2.Class = 0 AND 
                         t2.RN > t1.RN )