我有一个表格,我希望过滤所有行代码,生命和TC等于同一查询的结果,这些行是按ID过滤的
ID Code|Life|TC|PORT
62 XX101 1 1 1
63 XX101 1 1 2
64 AB123 1 1 1
65 AB123 1 1 2
66 AB123 1 1 3
67 CD321 1 1 1
68 CD321 1 1 2
这是我提出的最好的,但它看起来效率不高。
select ID from #table
where Code = (Select Code from #table where ID = @Port1) and
Life = (Select Life from #table where ID = @Port1) and
TC = (Select TC from #table where ID = @Port1)
答案 0 :(得分:2)
以下是您需要的查询:
select t2.*
from #table t1
join #table t2 on t1.Code = t2.Code and
t1.Life = t2.Life and
t1.TC = t2.TC and
t1.PORT = t2.PORT
where t1.id = @Port1
使用cross apply
:
select ca.*
from #table t1
cross apply (select * from #table t2 where t1.Code = t2.Code and
t1.Life = t2.Life and
t1.TC = t2.TC and
t1.PORT = t2.PORT) ca
where where t1.id = @Port1
使用cte
:
with cte as(select * from #table where id = @Port1)
select t.*
from #table t
join cte c on t.Code = c.Code and
t.Life = c.Life and
t.TC = c.TC and
t.PORT = c.PORT
答案 1 :(得分:1)
您可以为此方案使用EXIST语句
{{1}}
答案 2 :(得分:1)
您的代码看起来提供了与
相同的结果SELECT ID
FROM #table AS tbl1
INNER JOIM#table AS tbl2 on
tbl2.ID =@Port1 AND
tbl1.Life =tbl2.Life AND
tbl1.TC =tbl2.TC
但它更贵 您总是要求在where子句下的选择中使用相同的记录。 然后每次你选择一个不同的字段来匹配。 但请注意,因为如果有多个带有该ID的记录,则查询会产生错误,因为您使用了=运算符,它只需要检查的字段的一个实例。
答案 3 :(得分:0)
使用窗口函数:
;WITH CTE AS (
SELECT *, RANK() OVER (ORDER BY [Code], [Life], [TC]) AS grp
FROM mytable
), CTE2 AS (SELECT grp FROM CTE WHERE ID = @Port1)
SELECT *
FROM CTE
WHERE grp = (SELECT grp FROM CTE2)
上面的查询找到[Code], [Life], [TC]
所属的ID = @Port1
分区,然后选择该分区的所有行。