2017-02-16 46 views
0

我想獲得用戶ID的地方爲他們每個條目都有空的結束日期。例如找到所有的ID,其中日期值爲null

Userid | EndDate 
123 | NULL 
123 | NULL 
124 | 2016-01-01 
124 | NULL 
123 | NULL 
123 | NULL 
125 | 2016-01-01 
126 | NULL 

所以我只想要回123和126

列表

看起來似乎會有一個簡單的方法來做到這一點,但我沒有想到它。

在此先感謝您的幫助。

+0

什麼問題? 'WHERE EndDate IS NULL' – Barmar

+0

我只想要一個所有UserID的列表都有空的條目,124有一個NULL和一個日期,125沒有NULL,但是有一個日期。 123和126都有NULL,所以我想提取它們。 – KLD

回答

0
select Userid 
from sometable 
group by Userid 
having count(EndDate) = 0 

http://rextester.com/QJSWV55265

count(EndDate)將返回0如果只NULL值存在爲Userid

如果你有一個users表和適當的索引,一個可能會更快:

select Userid 
from users u 
where not exists (
    select * 
    from sometable t 
    where t.Userid = u.Userid 
    and t.EndDate is not null 
) 

UPDATE相反查詢(GET Userid當所有條目AR NOT NULL)將是:

select Userid 
from sometable 
group by Userid 
having count(EndDate) = count(Userid) 

http://rextester.com/FUKPLP59441

+0

非常好,感謝您的幫助,快速跟進。如果我想要相反的話: Userid |結束日期 123 | 2016-01-01 123 | NULL 124 | NULL 124 | 2016-01-01 123 | 2016-01-01 123 | NULL 125 | 2016-01-01 126 | NULL 其中我想拉125和124,因爲所有的值都不爲空,126只有一個NULL,123有一個非空的值... – KLD

+0

@KLD您可以將HAVING子句更改爲'having count( EndDate)= count(Userid)'。或者接受第二個查詢(或其他兩個答案中的一個),並將't.EndDate不爲空'更改爲't.EndDate爲空'。 –

0

你可以得到所有用戶標識符的列表,一個非空的結束日期,然後使用NOT IN排除它們。

SELECT DISTINCT userid 
FROM yourTable 
WHERE userid NOT IN (
    SELECT userid 
    FROM yourTable 
    WHERE EndDate IS NOT NULL) 
0

使用NOT EXISTS和一個子查詢做到這一點:

select distinct 
    `userid` 
from yourtable t1 
where not exists (
    select 1 
    from yourtable t2 
    where t1.userid = t2.userid 
    and t2.enddate is not null 
) 

demo這裏。

相關問題