2015-11-12 195 views
1

我有一张表,我想过滤所有具有代码,生命和TC等于选择结果的行在同一个表查询过滤通过IDSQL:通过从3列选择结果筛选同一个表中的多列,选择结果

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

预期结果是什么(提供表格数据)? – jarlh

回答

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 
+0

@ user1781272这些都使用示例数据返回一条记录......如果仅通过ID选择,它会更容易吗? – JamieD77

1

你可以使用一个EXIST语句这种情况下

SELECT 
    ID 
FROM 
    #table t1 
WHERE 
    EXISTS (SELECT 
       * 
      FROM 
       #table t2 
      WHERE 
       t2.ID = @Port1 
       AND t2.Code = t1.Code 
       AND t2.Life = t1.Life 
       AND t2.TC = t1.TC) 
1

你的代码看起来提供的

SELECT ID 
FROM #table AS tbl1 
INNER JOIM#table AS tbl2 on 
    tbl2.ID [email protected] AND 
    tbl1.Life =tbl2.Life AND 
    tbl1.TC =tbl2.TC 

相同的结果,但它更昂贵 你问总是在选择where子句下相同的记录。 然后每次选择不同的字段进行匹配。 但请注意,因为如果存在具有该ID的多个记录,则您的查询会发出错误,因为您使用了=运算符,所以它只会期望您检查的字段的一个实例。

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所属,然后选择该分区中的所有行。