我在SQL Server中有两个数据库表。我想有一个查询结果,将运算符名称绑定到另一个表中的行记录。即对于"表B"中的每一行记录,它将检查在事件发生时登录的操作员。例外情况是没有操作员登录,因此结果中会有一个空字段。
下面的屏幕截图概述了两个表以及样本结果的外观。任何帮助都将不胜感激......我已经离开了我的联盟。
Tom 10/01/2014 12:00 10/01/2014 12:09
Dick 10/01/2014 12:10 10/01/2014 12:35
Harry 10/01/2014 12:40 10/01/2014 12:45
10/01/2014 12:03 A
10/01/2014 12:15 B
10/01/2014 12:36 A
Tom 10/01/2014 12:03 A
Dick 10/01/2014 12:15 B
"没有操作员" 10/01/2014 12:36 A
答案 0 :(得分:2)
尝试这样的外部申请:
SELECT a.OperatorName
,b.TIMESTAMP
,b.EventName
FROM tableB b
OUTER APPLY (
SELECT ISNULL(a.OperatorName,'No Operator')
FROM tableA
WHERE b.TIMESTAMP BETWEEN a.LogOnTime
AND a.LogOutTime
) AS a
答案 1 :(得分:2)
我会用明确的left join
:
SELECT COALESCE(a.OperatorName, 'No Operator') as Operator, b.TIMESTAMP, b.EventName
FROM tableB b LEFT JOIN
tableA a
ON b.Timestamp BETWEEN a.LogOnTime and a.LogOutTime;