如何根据组内的字符串值选择属性

时间:2016-11-09 13:52:37

标签: sql database oracle

表名:副本

+------------------------------------+
|   group_id  |  my_id  |  stuff     |  
+------------------------------------+

|     900    |    1     |      Y     | 
|     900    |    2     |      N     | 
|     901    |    3     |      Y     | 
|     901    |    4     |      Y     | 
|     902    |    5     |      N     | 
|     902    |    6     |      N     | 
|     903    |    7     |      N     | 
|     903    |    8     |      Y     | 
---------------------------------------

输出应为:

+------------------------------------+
|   group_id  |  my_id  |  stuff     |  
+------------------------------------+
|     900    |    1     |      Y     | 
|     903    |    8     |      Y     | 
--------------------------------------

你好,我有一张表,我必须根据stuff字段中的正(Y)值识别group_id中的'好'记录。我需要完整的记录,其中只有一个值符合此标准。如果两个填充值都是Y或两者都是N,则不应选择它们。看起来这应该很简单,但我不确定如何继续。

5 个答案:

答案 0 :(得分:2)

这里的一个选择是对每个group_id使用条件聚合,如果它包含是和否答案,则保留一个组。

WITH cte AS (
    SELECT group_id
    FROM Copies
    GROUP BY group_id
    HAVING SUM(CASE WHEN stuff = 'Y' THEN 1 ELSE 0 END) > 0 AND
           SUM(CASE WHEN stuff = 'N' THEN 1 ELSE 0 END) > 0
)

SELECT c1.*
FROM Copies c1
INNER JOIN cte c2
    ON c1.group_id = c2.group_id
WHERE c1.stuff = 'Y'

此解决方案的一个优点是它将显示匹配记录的所有列。

答案 1 :(得分:1)

select group_id, 
       min(my_id) 
          keep (dense_rank first order by case stuff when 'Y' then 0 end) as my_id, 
       'Y' as stuff
from   table_1
group by group_id
having min(stuff) != max(stuff)

答案 2 :(得分:0)

with rows as(
select group_id, my_id, sum(case when stuff = 'Y' then 1 else 0 end) c 
  from copies 
  group by group_id, my_id)
select c.* 
  from copies c inner join rows r on (c.group_id = r.group_id and c.my_id = r.my_id) 
  where r.c = 1;

答案 3 :(得分:0)

试试这个:

SELECT t1.*
FROM copies t1
JOIN (
   SELECT group_id
   FROM copies 
   GROUP BY group_id
   HAVING COUNT(CASE WHEN stuff = 'Y' THEN 1 END) = 1 AND 
          COUNT(CASE WHEN stuff = 'N' THEN 1 END) = 1
) t2 ON t1.group_id = t2.group_id
WHERE t1.stuff = 'Y'

只要group_id值出现在情侣身上,就可以使用。

答案 4 :(得分:0)

试试这个:

SELECT C.*
FROM COPIES C,
     COPIES C2
WHERE C.STUFF='Y'    
AND C2.STUFF='N'
AND C.GROUP_ID=C2.GROUP_ID