如何从内部查询中获取不同的值? 场景:
我有一个表: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/