仅在按顺序排列时省略重复

时间:2017-02-01 19:45:43

标签: sql sql-server tsql sql-server-2016

我有一个查询返回以下信息。我使用了Over(PARTITION BY来包含行号。每次我的work_center_S开始一个新的Order#时我都会捕获,但是当part_number与之前的order / row相同时,我想要排除新订单的开头。我无法使用DISTINCT函数,因为part_number可能每天出现多次,每次发生这种变化时我都需要捕获。

[![查询返回] [1]] [1]   [1]:https://i.stack.imgur.com/IKvsR.jpg

+----+--------+---------------+-------------+------+
| rn | Order# | work_center_S | part_number | Hour |
+----+--------+---------------+-------------+------+
| 1  | 7098   | TB312         | 37203       | 1    |
+----+--------+---------------+-------------+------+
| 2  | 8797   | TB312         | 37194       | 4    |
+----+--------+---------------+-------------+------+
| 3  | 8802   | TB312         | 37355       | 11   |
+----+--------+---------------+-------------+------+
| 4  | 0946   | TB312         | 37194       | 15   |
+----+--------+---------------+-------------+------+
| 5  | 0698   | TB312         | 37203       | 18   |
+----+--------+---------------+-------------+------+
| 6  | 0699   | TB312         | 37203       | 21   |
+----+--------+---------------+-------------+------+

1 个答案:

答案 0 :(得分:2)

我认为没有-1 part_number

select  Order#,work_center_S,part_number,Hour

from   (select  *
               ,lag(part_number,1,-1) over
                (
                    partition by  work_center_S
                    order by      Hour
                ) as prev_part_number

        from    mytable
        ) t

where   part_number <> prev_part_number

-

+--------+---------------+-------------+------+
| Order# | work_center_S | part_number | Hour |
+--------+---------------+-------------+------+
| 7098   | TB312         | 37203       | 1    |
+--------+---------------+-------------+------+
| 8797   | TB312         | 37194       | 4    |
+--------+---------------+-------------+------+
| 8802   | TB312         | 37355       | 11   |
+--------+---------------+-------------+------+
| 946    | TB312         | 37194       | 15   |
+--------+---------------+-------------+------+
| 698    | TB312         | 37203       | 18   |
+--------+---------------+-------------+------+