获取不包含某些数据的行

时间:2017-10-03 13:46:57

标签: sql sql-server

我正在使用SQL查询

我试图得到ChildId他/她的父母(Some_Code_Of_Parent)都不包含特定数据(在这种情况下为50)。

 ParentId | ChildId | Some_code_of_Parent 
 11       |    2    |                  50    
 22       |    2    |                   0

非常感谢任何帮助。

请注意,此表包含许多儿童和家长的类似数据。这些只是两行作为例子。

在这种情况下,我希望得到0行的结果。 如果两个父母(11,22)在Some_code_of_Parent中的值为50,那么结果将是带有子ID的1行。

4 个答案:

答案 0 :(得分:1)

这将只返回那些每个父节点都有Some_code_of_Parent = 50的childId。

DECLARE @valueToCheck INT = 50

SELECT DISTINCT ChildId FROM TABLE_NAME WHERE ChildId NOT IN(
SELECT ChildId FROM TABLE_NAME a 
WHERE EXISTS (SELECT 1 FROM TABLE_NAME 
WHERE ChildId = a.ChildId AND Some_code_of_Parent <> @valueToCheck))

DECLARE @valueToCheck INT = 50

SELECT DISTINCT ChildId FROM TABLE_NAME  WHERE ChildId NOT IN(
SELECT ChildId FROM TABLE_NAME  WHERE Some_code_of_Parent <> @valueToCheck 
GROUP BY ChildId, Some_code_of_Parent)

DECLARE @valueToCheck INT = 50

SELECT ChildId FROM TABLE_NAME 
GROUP BY ChildId 
HAVING avg(cast(Some_code_of_Parent as decimal(20,2))) = @valueToCheck

答案 1 :(得分:0)

Select 
    ParentID 
From MyTable 
Where Some_Code_Of_Parent <> 50;

或多个值,如50,100,150

Select 
    ParentID 
From MyTable 
Where Some_Code_Of_Parent Not In (50, 100, 150) And Some_Code_Of_Parent Is Not Null;

答案 2 :(得分:0)

你可以使用它。

SELECT 
    ChildId 
FROM 
    MyTable 
GROUP BY 
    ChildId 
HAVING
    MAX(Some_code_of_Parent) = MIN(Some_code_of_Parent)
    AND MAX(Some_code_of_Parent) IN (0,50)

答案 3 :(得分:0)

尝试子查询而不是条件。

Select distinct ChildId from [Table] 
where ChildId not in (select ChildId from [Table] where Some_code_of_Parent = 50)