Sql 从内部查询中查找不同的值
如何从内部查询中获取不同的值? 情景: 我有一个表:Sql 从内部查询中查找不同的值,sql,database,Sql,Database,如何从内部查询中获取不同的值? 情景: 我有一个表:MyData,其中包含ID列和Starttime列。 ID是一个十六进制字符串 starttime是一个时间戳。 ID和starttime可以为空 以下是表格的外观: 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 <
MyData
,其中包含ID列和Starttime列。
ID是一个十六进制字符串
starttime是一个时间戳。
ID和starttime可以为空
以下是表格的外观:
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>
我试过:
这似乎会产生所有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查询对我来说似乎很直接,这里是否有明显的错误
其他信息:
My DB是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不象“”
此条件不测试null。使用id不为空
子查询只返回所有没有空starttime的ID。因此,您的查询不会检查每个id的starttime的所有值,它相当于:
select distinct ID from MyData where id not like '' and starttime is not null;
第二个查询的功能与第一个查询相同—您刚刚为子查询添加了一个别名。第一个选项似乎工作得很好。我开始的问题有什么内在的错误。@Ayusman我在答案中添加了一些信息。查询中的主要问题是,您只是过滤数据,只保留不为null的starttime行,但需要扫描每个id的所有starttime。
select distinct(ID) from Mydata
where ID in (select ID from MyData
where id not like '' and starttime is not null);
select distinct ID from MyData where id not like '' and starttime is not null;