SQL select rows with only a certain value in them

前端 未结 5 1409
半阙折子戏
半阙折子戏 2020-12-28 19:49

I have a table as such

Col 1 Col 2 Col 3
1       A     1
2       A     2
3       B     1
4       C     1
5       C     2
6       D     1

Ho

相关标签:
5条回答
  • 2020-12-28 20:08

    It's a bit hard to know exactly what you're trying to get, but this is my best guess:

    SELECT * FROM theTable WHERE col2 NOT IN
      (SELECT col2 FROM theTable WHERE col3 <> 1)
    
    0 讨论(0)
  • 2020-12-28 20:13
    SELECT col2
    FROM your_table
    GROUP BY col2
    HAVING MAX(col3) = 1 AND MIN(Col3) = 1
    

    Or

    SELECT a.col2 
    FROM your_table a
    WHERE a.col3=1 AND NOT EXISTS(SELECT *
                                  FROM your_table b 
                                  WHERE a.col2=b.col2 AND b.col3<>1)
    
    0 讨论(0)
  • 2020-12-28 20:14
    ;with T ([Col 1], [Col 2], [Col 3]) as
    (
    select 1,       'A',     1 union all
    select 2,       'A',     2 union all
    select 3,       'B',     1 union all
    select 4,       'C',     1 union all
    select 5,       'C',     2 union all
    select 6,       'D',     1
    )
    
    
    select *
    from T
      left outer join 
        (
          select distinct [Col 2] 
          from T
          where [Col 3] <> 1
        ) as T2
      on T.[Col 2] = T2.[Col 2]
    where T.[Col 3] = 1 and
          T2.[Col 2] is null
    
    0 讨论(0)
  • 2020-12-28 20:21

    What you are probably looking for is WHERE clause.

    SELECT * FROM YouTable WHERE col3 = 1 AND col2 in ('B','D');
    
    0 讨论(0)
  • 2020-12-28 20:27
    SELECT * FROM #temp t1
    WHERE EXISTS 
    (
    select Col2 from #Temp t2 
    WHERE t2.Col2 = t1.Col2
    group by col2 
    having count(col3) = 1
    )
    

    tested with MS SQL2008 and the following (so if my answer is not the correct one it may halp others test theirs...):

    CREATE TABLE #temp 
    ( 
        Col1 INT, 
        Col2 CHAR(1),
        Col3 INT
    )
    
    INSERT INTO #Temp    
        (Col1, Col2, Col3)
    SELECT    1,'A',1
    UNION
    SELECT    2,'A',2
    UNION
    SELECT  3,'B', 1
    UNION 
    SELECT 4,'C',1
    UNION 
    SELECT 5,'C',2
    UNION 
    SELECT 6,'D',1
    
    SELECT * FROM #temp t1
    WHERE EXISTS 
    (
    select Col2 from #temp t2 
    WHERE t2.Col2 = t1.Col2
    group by col2 
    having count(col3) = 1
    )
    
    DROP TABLE #temp
    
    0 讨论(0)
提交回复
热议问题