如何从内部查询中获取不同的值? 方案:
我有一个表:MyData
,其中包含列ID和启动时间。
ID是十六进制字符串
和starttime是一个时间戳。
ID和starttime可以为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>
我希望在其的starttime列中获得不具有任何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
选择不同的查询对我来说似乎很简单,这里有什么明显的错误吗?
其他信息: 我的数据库是MS Access DB,* .accdb类型数据库。
答案 0 :(得分:0)
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
子查询只返回所有没有null starttime的id。因此,您的查询不会检查每个ID的所有starttime值,它等同于:
select distinct ID from MyData where id not like '' and starttime is not null;
第二个查询与第一个查询的作用相同 - 您只是为子查询添加了别名。