0

我有一个由 RepId 及其日期组成的表。

Table: 1
RepID   Date
108981  2013-04-09 00:00:00.000
108981  2013-04-09 00:00:00.000
108982  2013-04-10 00:00:00.000
108982  2013-04-11 00:00:00.000
108983  2013-04-11 00:00:00.000
108983  2013-04-11 00:00:00.000

我有另一个表,它由 RepId 和它们的 logTime 组成。

Table: 2
repID   logTime
108981  2013-04-09 00:00:00.000
108981  2013-04-09 00:00:00.000
108982  2013-04-11 00:00:00.000
108983  2013-04-11 00:00:00.000
108983  2013-04-11 00:00:00.000
108984      2013-04-10 00:00:00.000

我想要表 1 中的 RepId 计数,当表 2 中的该代表不存在日志时间时。

在这种情况下,我需要输出为

repId       RepCount
108982      1

由于 RepId - 108982 的表 2 中不存在日期“2013-04-10 00:00:00.000”。

我已将查询用作

select
    t1.RepID, count(t1.RepID) as 'Rep Count'
from
    table1 t1
where
    not exists
    (select t2.repID from table2 t2 where
     CONVERT(date, t2.logTime) between '2013-04-08 00:00:00.000' and '2013-04-11 00:00:00.000')
group by
    t1.RepID

但它总是什么都不返回。请帮助摆脱这个问题....

4

5 回答 5

0
select
    t1.RepID, count(t1.RepID) as 'Rep Count'
from
    table1 t1
where
    not exists
    (select * from table2 t2 where
     t2.RepID = t1.RepID and t2.LogTime = t1.Date)
group by
    t1.RepID

SQLFiddle 演示

于 2013-05-08T13:30:57.293 回答
0

您可以在此处使用 LEFT OUTER JOIN。

SELECT 
  t1.repID, COUNT(t1.repID)  
FROM
  table1 t1
LEFT OUTER JOIN
  table2 t2
ON
  t1.repID = t2.repID
AND
  t1.Date = t2.logTime
WHERE
  t2.repID IS NULL
GROUP BY
  t1.repID
于 2013-05-08T13:28:16.347 回答
0

我认为您想将其表达为not in

select t1.RepID, count(t1.RepID) as 'Rep Count'
from table1 t1
where t1.repid not in (select t2.repID
                       from table2 t2
                       where CONVERT(date, t2.logTime) between '2013-04-08 00:00:00.000' and '2013-04-11 00:00:00.000'
                       )
group by t1.RepID

或者使用相关子查询或left outer join.

您的查询的问题是您正在寻找该期间任何记录的存在(或不存在),并且必须存在。您确实想查找给定 repId 的记录。

于 2013-05-08T13:28:45.790 回答
0

问题是您没有将 not exists 中的子查询与外部查询相关联,因此 not exists 子句始终返回 false。尝试这样的事情:

select
    t1.RepID, count(t1.RepID) as 'Rep Count'
from
    table1 t1
where
    not exists
    (select t2.repID from table2 t2 where t2.repId = t1.repId and
     CONVERT(date, t2.logTime) between '2013-04-08 00:00:00.000' and '2013-04-11 00:00:00.000')
group by
    t1.RepID
于 2013-05-08T13:30:03.203 回答
0

between将涵盖给定的开始和结束日期以及table2 logtime2013-04-11 00:00:00.000 将处于介于两者之间的条件,这就是您没有获得任何记录的原因

你应该用过r.RepId not in

看这个演示, SQLFiddle DEMO

要么你使用> 和 <

select
    t1.RepID, count(t1.RepID) as 'Rep Count'
from
    table1 t1
where t1.RepID
    not in
    (select t2.repID from table2 t2 where
     t2.logTime > '2013-04-08 00:00:00.000' and t2.logTime < '2013-04-11 00:00:00.000')
group by
    t1.RepID

或者你的结果是正确的改变你的 table2 值

108982, '2013-04-11 01:00:00.000'


select
    t1.RepID, count(t1.RepID) as 'Rep Count'
from
    table1 t1
where t1.RepID
    not in
    (select t2.repID from table2 t2 where
     t2.logTime between '2013-04-08 00:00:00.000' and '2013-04-11 00:00:00.000')
group by
    t1.RepID
于 2013-05-08T13:44:19.760 回答