Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/72.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.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 Server:如何使用不同的查询合并这两个查询_Sql_Sql Server_Sql Server 2012 - Fatal编程技术网

SQL Server:如何使用不同的查询合并这两个查询

SQL Server:如何使用不同的查询合并这两个查询,sql,sql-server,sql-server-2012,Sql,Sql Server,Sql Server 2012,我有一个查询,它获取不同设备ID的列表,现在我想将该查询与另一个具有内部联接的查询联接 这是我的第一个问题 Select distinct deviceid from session where cast(createdon as date) between '01/01/2018' and '01/30/2018' and len(deviceid) > 10 该查询返回我需要的不同设备ID。现在,我想使用该查询中的DeviceID,并将其替换为该查询中的DeviceID 第

我有一个查询,它获取不同设备ID的列表,现在我想将该查询与另一个具有内部联接的查询联接

这是我的第一个问题

Select distinct deviceid 
from session 
where cast(createdon as date) between '01/01/2018' and '01/30/2018' 
  and len(deviceid) > 10
该查询返回我需要的不同设备ID。现在,我想使用该查询中的DeviceID,并将其替换为该查询中的DeviceID

第二个问题:

select f.PracticeID, F.Name, D.DeviceID, d.SerialNumber 
from device d
inner join facility f on f.id = d.locationid
inner join session s on s.deviceid = d.deviceid 
where d.deviceID = 'deviceID'

我如何合并这两个?我想从第一个查询中获得结果,并将其用于第二个查询设备ID列。现在,我正在手动执行从第一个查询得到的第二个查询中的
DeviceID
。我正在使用SQL Server 2012

是否要从第二个查询中获取与第一个查询不同的DeviceID的所有数据?这应该可以做到

select f.PracticeID,F.Name,D.DeviceID,d.SerialNumber from device d
inner join facility f on f.id=d.locationid
inner join session s on s.deviceid=d.deviceid 
where d.deviceID in (
     Select distinct deviceid from session where cast(createdon as date) between 
     '01/01/2018' and '01/30/2018' and len(deviceid)>10
)

您可以使用子查询来实现这一点:-

select f.PracticeID,F.Name,D.DeviceID,d.SerialNumber from ( Select distinct deviceid from session where cast(createdon as date) between 
'01/01/2018' and '01/30/2018' and len(deviceid)>10) d
inner join facility f on f.id=d.locationid
inner join session s on s.deviceid=d.deviceid 
where d.deviceID='deviceID'

小心那些日期。您应该使用ANSI日期格式YYYYMMDD。如果使用这些字符串,它们可能会根据本地日期格式(可针对当前连接进行更改)和基于安装语言的默认更改而被误解。