[英]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;
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.