簡體   English   中英

從內部查詢中查找不同的值

[英]Find distinct values from an inner query

如何從內部查詢中獲取不同的值? 場景

我有一個表:具有列ID和啟動時間的MyData ID是一個十六進制字符串,開始時間是一個時間戳。 ID和開始時間可以為空。

表格外觀如下:

ID           StartTime
01655a70    2014-10-24 06:22:03.0
01655a70    2014-10-24 06:22:03.0
b752        2014-10-15 03:19:03.0
b752        <null>
3922b       2014-10-15 03:19:03.0
d98cb       <null>

我想獲取在其起始時間列中沒有任何NULL值的不同ID值。

Expected result should be:

01655a70
3922b

我努力了:

select distinct(ID) from Mydata where ID in (select ID from MyData where id not like '' and starttime is not null)


select distinct(inner.ID) from (select ID from MyData where id not like '' and starttime is not null) as inner

這似乎會產生所有ID條目,包括具有空值的ID條目。

還看了SO帖子

http://stackoverflow.com/questions/23278387/options-for-returning-distinct-values-across-an-inner-join

and 

http://stackoverflow.com/questions/13149857/select-distinct-on-inner-join-query-filtering-by-multiple-values-on-a-single-col

選擇不同的查詢對我來說似乎很直截了當,這顯然有什么問題嗎?

附加信息:我的數據庫是MS Access DB * .accdb類型數據庫。

select t.id from (
  select id, count(*) as n_all, 
             count(starttime) as n_time
  from Mydata 
  group by id
) t 
where t.n_all = t.n_time;

count(*)計算所有行
count(col)計算不為空的col

另外一個選項:

select distinct m1.id from Mydata m1
where not exists (select 1 from Mydata m2 where m2.id = m1.id and m2.starttime is null);

您的查詢:

select distinct(ID) from Mydata 
where ID in (select ID from MyData 
             where id not like '' and starttime is not null);

id not like ''此條件不測試null。 使用id is not null

子查詢只返回開始時間不為空的所有ID。 因此,您的查詢不會檢查每個id的所有starttime值,它等效於:

select distinct ID from MyData where id not like '' and starttime is not null;

第二個查詢與第一個查詢具有相同的功能-您剛剛為子查詢添加了別名。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM