sql - 从内部查询中查找不同的值

标签 sql database

如何从内部查询中获取不同的值? 场景:

我有一个表:MyData,其中包含 ID 和 Starttime 列。 ID 是一个十六进制字符串 starttime 是一个时间戳。 ID 和开始时间可以为 null。

表格如下:

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 条目,包括具有空值的条目。

还查看了 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

select distinct 查询对我来说似乎很直接,这里有什么明显的错误吗?

附加信息: 我的数据库是 MS Access 数据库,*.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 的所有开始时间值,它等效于:

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

第二个查询与第一个查询做同样的事情——你只是为你的子查询添加了一个别名。

关于sql - 从内部查询中查找不同的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26904745/

相关文章:

mysql - 如果不存在则插入行而不会出现死锁

mysql - 跨数据库连接

SQL 'AT TIME ZONE',查询范围和 'SELECT' 所有列 (tablename.*) 表达式

python - 如何在django db集合自定义查询中选择数据库?

php - 将 Silverstripe 迁移到 Wordpress - 更改网络平台

MySQL - 仅获取特定 parent 的 child

sql - 设置 deadlock_priority 不会使低优先级 session 成为受害者

mysql - 使用sql显示列中每个元素的总和?

java - 是否可以保存从http读取的zip文件并直接将其保存到Databse中,而无需在java中物理创建它

database - 没有 FROM 关键字的 Sparql