简体   繁体   English

T-SQL查询以仅显示行之间的差异

[英]T-SQL query to show only differences between rows

I have a query that outputs the following dataset: 我有一个查询,输出以下数据集:

在此处输入图片说明

I need to find a way to find instance where the unitid column and the stat column do not match. 我需要找到一种方法来查找unitid列和stat列不匹配的实例。 An example would be if unitid = 2, CleanCode = 10 and stat = Started and the next row below was unitid = 2, CleanCode = 2 and stat = Not Started . 例如,如果unitid = 2, CleanCode = 10并且stat = Started ,而下面的下一行是unitid = 2, CleanCode = 2并且stat = Not Started

How can I create a query to find those differences? 如何创建查询以查找那些差异?

Thanks 谢谢

One option is a self join: 一种选择是自我联接:

SELECT DISTINCT t1.unitId
FROM yourTable t1
INNER JOIN yourTable t2
    ON t1.unitId = t2.unitId AND
       t1.id <> t2.id AND
       t1.cleanCode <> t2.cleanCode AND
       t1.stat <> t2.stat;

Demo 演示版

I added one extra record to your sample data, because none of the data you actually showed us would end up in your expected result set. 我在您的样本数据中添加了一条额外的记录,因为您实际显示给我们的任何数据都不会最终出现在您的预期结果集中。

Assuming you have a column that specifies the ordering, use lag() : 假设您有一列指定顺序,请使用lag()

select t.*
from (select t.*,
             lag(stat) over (partition by unitcode order by <ordering column>) as prev_stat
      from t
     ) t
where prev_stat <> stat;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM