需要一个查询来查找多行中具有相同id值的不同值的记录

时间:2017-08-18 06:00:26

标签: sql sql-server database

我真的很困惑。

我需要找到CustTreeNodeId = 55且PreferenceID = 1),(OverrideValue = 56且PreferenceID =的OverrideValue个{} 1),(PreferenceID = 58和OverrideValue is not null)。

记录应该包含所有三个PreferenceID并且应该满足上述所有三个条件。

示例 - 请参见屏幕截图中的CustTreeNodeID = 76853551-7ACD-48E1-BEFF-0000498A144C

This is my table

4 个答案:

答案 0 :(得分:1)

这些将为您提供所需的CustTreeNodePreferenceOverrideID

SELECT CustTreeNodePreferenceOverrideID
FROM   yourtable
WHERE  ( condition 1 )
OR     ( condition 2 )
OR     ( condition 3 )
GROUP BY CustTreeNodePreferenceOverrideID
HAVING COUNT(*) = 3

答案 1 :(得分:1)

在这种情况下你可以使用EXISTS子句

select 
    CustTreeNodeId 
from yourtable t1
where 
    exists
        ( 
            select  1 from yourtable t2 
            where t2.CustTreeNodeId =t1.CustTreeNodeId  
            and 
            (t2.PreferenceID = 55 and t2.OverrideValue = 1 )
        )
    and exists
        ( 
            select  1 from yourtable t3 
            where t3.CustTreeNodeId =t1.CustTreeNodeId  
            and 
            (t3.PreferenceID = 56 and t3.OverrideValue = 1)
        )
    and exists
        (
            select  1 from yourtable t4 
            where t4.CustTreeNodeId =t1.CustTreeNodeId  
            and
            (t4.PreferenceID = 58 and t4.OverrideValue is not null)
        )

答案 2 :(得分:1)

SELECT CustTreeNodeID 
FROM myTable 
WHERE   (PreferenceID = 55 and OverrideValue = 1 ) 
OR  (PreferenceID = 56 and OverrideValue = 1)
OR (PreferenceID = 58 and OverrideValue is not null)
GROUP BY CustTreeNodeID 
HAVING COUNT(PreferenceID)=3

答案 3 :(得分:1)

试试这个:

SELECT CustTreeID 
FROM   yourtable t
WHERE  (t.PreferenceID IN (55,56) AND t.OverrideValue=1)
OR (t.PreferencedID =58 AND t.OverrideValue IS NOT NULL)
GROUP BY CustTreeID
HAVING COUNT(t.OverrideValue) = 3