Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 同一表中记录的差异_Sql_Sql Server_Join - Fatal编程技术网

Sql 同一表中记录的差异

Sql 同一表中记录的差异,sql,sql-server,join,Sql,Sql Server,Join,我有一个表,从中获取两个时间间隔的记录,如下所示 Query1: select distinct(Id) from dbo.tableA where datediff(hour, dtCreate, getdate()) < 24 Query2: select distinct(Id) from dbo.tableA where datediff(hour, dtCreate, getdate()) < 48 and datediff(hour, dtCreate, ge

我有一个表,从中获取两个时间间隔的记录,如下所示

Query1:

select distinct(Id) 
from dbo.tableA 
where datediff(hour, dtCreate, getdate()) < 24

Query2:
select distinct(Id) 
from dbo.tableA 
where datediff(hour, dtCreate, getdate()) < 48
and datediff(hour, dtCreate, getdate()) > 24
Query1:
选择不同的(Id)
来自dbo.tableA
其中datediff(hour,dtCreate,getdate())<24
问题2:
选择不同的(Id)
来自dbo.tableA
其中datediff(hour,dtCreate,getdate())<48
和datediff(hour,dtCreate,getdate())>24
查询1返回50条记录,查询2返回45条记录。
在此之后,我想找到那些在查询2中不存在但在查询1中存在的记录。谁能建议我怎么做??提前谢谢

您似乎想要计算设置的差异,因此您可以使用
除了

select distinct(Id) 
from dbo.tableA 
where datediff(hour, dtCreate, getdate()) < 24
EXCEPT
select distinct(Id) 
from dbo.tableA 
where datediff(hour, dtCreate, getdate()) < 48
and datediff(hour, dtCreate, getdate()) > 24
选择不同的(Id)
来自dbo.tableA
其中datediff(hour,dtCreate,getdate())<24
除了
选择不同的(Id)
来自dbo.tableA
其中datediff(hour,dtCreate,getdate())<48
和datediff(hour,dtCreate,getdate())>24
使用:

选择Id
来自dbo.tableA
其中datediff(hour,dtCreate,getdate())<24
除了
选择Id
来自dbo.tableA
其中datediff(hour,dtCreate,getdate())<48
和datediff(hour,dtCreate,getdate())>24
;

(注意:我去掉了
DISTINCT
s,因为
EXCEPT
是隐式的;但是如果你想把
DISTINCT
留在那里,为了清楚起见,你绝对可以。)

如果我错了,请纠正我,但这里没有交叉点。查询1列出时间24。@bonsvr:我假设
Id
,不管它的名称如何,都不是表的唯一键。(否则,
distinct(Id)
也没有意义。)因此,两个查询之间的
Id
s可能存在一些重叠,即使没有单独的表记录可以重叠。@ruakh:是的,它的主键Id不能重复多次。@bonsvr:query1和query2之间没有交集。如果没有交集,query1单独会给出query2中不存在的记录。
SELECT Id
  FROM dbo.tableA
 WHERE datediff(hour, dtCreate, getdate()) < 24
EXCEPT
SELECT Id
  FROM dbo.tableA
 WHERE datediff(hour, dtCreate, getdate()) < 48
  AND datediff(hour, dtCreate, getdate()) > 24
;