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

表 2 の担当者の logtime が存在しない場合、表 1 の RepId の数が必要です。

この場合、出力が必要です

repId       RepCount
108982      1

日付「2013-04-10 00:00:00.000」は、RepId - 108982 のテーブル 2 に存在しないためです。

クエリを次のように使用しました

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

betweenは指定された開始日と終了日をカバーしますtable2 logtime2013-04-11 00:00:00.000 は between 条件に該当するため、レコードを取得できません

そして、あなたは使うべきだった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 に答える
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 に答える