如何比较同一个表 (SQL Server) 中的 2 行? [英] How do I compare 2 rows from the same table (SQL Server)?
问题描述
我需要创建一个后台作业来处理一个表,以查找在具有不同状态的特定 id 上匹配的行.它将行数据存储在一个字符串中,以将数据与具有匹配 id 的行进行比较.
I need to create a background job that processes a table looking for rows matching on a particular id with different statuses. It will store the row data in a string to compare the data against a row with a matching id.
我知道获取行数据的语法,但我以前从未尝试过比较同一个表中的 2 行.它是如何完成的?我是否需要使用变量来存储每个变量的数据?或者其他方式?
I know the syntax to get the row data, but I have never tried comparing 2 rows from the same table before. How is it done? Would I need to use variables to store the data from each? Or some other way?
(使用 SQL Server 2008)
(Using SQL Server 2008)
推荐答案
你可以根据需要多次加入一个表,它被称为 自加入.
You can join a table to itself as many times as you require, it is called a self join.
为表的每个实例分配一个别名(如下例所示)以区分一个.
An alias is assigned to each instance of the table (as in the example below) to differentiate one from another.
SELECT a.SelfJoinTableID
FROM dbo.SelfJoinTable a
INNER JOIN dbo.SelfJoinTable b
ON a.SelfJoinTableID = b.SelfJoinTableID
INNER JOIN dbo.SelfJoinTable c
ON a.SelfJoinTableID = c.SelfJoinTableID
WHERE a.Status = 'Status to filter a'
AND b.Status = 'Status to filter b'
AND c.Status = 'Status to filter c'
这篇关于如何比较同一个表 (SQL Server) 中的 2 行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!