2016-05-17 79 views
3

我有8条记录下面的:选择的记录不同的组,只有当所有记录某些列的有一定的价值

ID | Common ID | Reject 
------------------------- 
AB-1 | AB  | NULL 
AB-2 | AB  | YES 
AB-3 | AB  | NULL 
BB-1 | BB  | YES 
BB-2 | BB  | YES 
BB-3 | BB  | YES 
CB-1 | CB  | YES 
CB-2 | CB  | YES 
DB-1 | DB  | NULL 

我预期的结果是:

ID | Common ID | Reject 
------------------------- 
BB-1 | BB  | YES 
CB-1 | CB  | YES 

我只想当所有具有相同公共ID的记录的拒绝列为“是”时,获取不同的记录。

回答

3
select min(ID), [Common ID], max(Reject) 
from tablename 
group by [Common ID] 
having count(*) = count(case when Reject = 'YES' then 1 end) 

如果[通用ID]具有相同的行数为YES的数量,然后回吧!

HAVING子句的count(*)返回[Common ID]的总行数。如果Reject = Yes,则case表达式返回1,否则返回null。右侧count返回大小写返回非空值的行数(即,当拒绝为是时!)当行数相同时,HAVING为真!

编辑:

在此特定情况下,当拒绝列值似乎是yes或NULL,则HAVING可以简化为:

having count(*) = count(Reject) 

然而,如果其它值(像NO)稍后会在列中找到,这是行不通的。所以我建议原始HAVING条款!

+0

不错的一个+1 ..... – tharif

+0

不错...... btw,count(*)= count的实际值是多少(当Reject ='YES',然后是1结束时)''?我不太了解这条线。你能告诉我'count(*)'的值和'count的值(每个循环的Reject ='YES'然后1个结束时的情况? – Mark

+0

@Markorie,对我的回答添加了解释。 (作为评论太长。) – jarlh

1
SELECT MIN(ID), CommonID, MIN(Reject) as Reject 
FROM yourtable 
GROUP BY CommonID 
HAVING MIN(ISNULL(Reject, '')) = MAX(ISNULL(Reject, '')) 
AND  MIN(ISNULL(Reject, '')) = 'Yes' 

编辑:你有NULL值,则需要使用ISNULL()在列

+0

抱歉......仍在编辑。保存得太快 – Squirrel

0

WHERE子句用GROUP BY一个子查询。

SELECT ID, [Common ID], Reject 
FROM yourtable 
WHERE (SELECT SUM(LEN(a.Reject)) 
     FROM yourtable a 
     WHERE ID = a.ID 
     GROUP BY a.ID) IS NULL 

输出:

SQL小提琴:

0

使用row_number窗口函数和not exists。有点复杂,但应该做的工作:

with cte as(select *, row_number(partition by commonid order by id) rn from table) 
select c.* 
from cte c 
where c.rn = 1 and 
     not exists(select * from table t 
       where t.commonid = c.commonid and 
         (t.reject is null or t.reject <> 'yes')) 
0
SELECT MIN(ID) as ID, [Common ID], MIN(Reject) as Reject 
FROM Table1 
GROUP BY [Common ID] 
HAVING MIN(ISNULL(Reject, '')) = 'YES' 
0

这将帮助你

select 
(select top 1 ID from YourTable where CommonID= t.CommonID and reject=t.reject)ID, 
CommonID, 
Reject 
from YourTable T 
group by 
CommonID,reject 
having (Reject is not null) 
0

试试这个

SELECT MIN(ID) AS ID, ColumnID, MIN(Reject) AS Reject 
     FROM tableName 
     WHERE Reject='YES' AND ID LIKE '%1' 
     GROUP BY ColumnID 
0

这是实现最简单的方法你预期结果。

SELECT ID, [Common ID], Reject 
FROM YOURTABLE 
WHERE REJECT = 'YES' 
GROUP BY ID, COMMON ID 
相关问题