0

我有 2 个具有相同架构的表(THour_IN 和 THour_OUT): THour_IN 的列:名称|日期|HourIN THour_OUT 的列:名称|日期|HourOUT 我进行查询:

SELECT THour_IN.Name, THour_IN.date, THour_IN.HourIN, THour_OUT.HourOUT FROM THour_IN LEFT JOIN THour_OUT ON (Hour_IN.Name = THour_OUT.Name) AND (Hour_IN.date = THour_OUT.date);

但这在我的情况下是不正确的,因为我在表格中有多个具有相同日期的行。结果是:

Name   date       HourIN    HourOUT
AAA 24/11/2013  17:33:06    20:33:27
AAA 24/11/2013  17:33:06    16:36:06
AAA 24/11/2013  07:33:27    20:33:27
AAA 24/11/2013  07:33:27    16:36:06
BBB 18/11/2013              16:36:06
BBB 19/11/2013  07:33:30    
BBB 21/11/2013  07:29:24    08:33:22
BBB 22/11/2013  07:33:30    16:34:53

日期应为 24/11/2013 First HourIN(07:33:27) with First HourOUT (16:36:06), Second HourIN (17:33:06) with Second HourOUT (20:33:06) Any想法?

4

2 回答 2

1

构建线段,然后与线段相交。

SELECT
  P1.Name, P1.date, P1.HourIN, P1.HourOUT
FROM (
  SELECT
    I.Name, I.date, I.HourIN, O.HourOUT
  FROM
    THour_IN AS I
    LEFT JOIN THour_OUT AS O
      ON (I.Name = O.Name) AND (I.date = O.date)
        AND I.HourIN < H.HourOUT
) AS P1
INNER JOIN (
  SELECT
    I.Name, I.date, I.HourIN, O.HourOUT
  FROM
    THour_IN AS I
    LEFT JOIN THour_OUT AS O
      ON (I.Name = O.Name) AND (I.date = O.date)
        AND I.HourIN < H.HourOUT
) AS P2
  ON P1.name = P2.name AND P1.date = P2.date
    AND P1.HourIN <> P2.HourIN and P1.HourOUT <> P2.HourOUT
    AND P1.HourOUT > P2.HourIN
    AND (P1.HourIN = P2.HourIN AND P1.HourOUT < P2.HourOUT
          OR P1.HourIN > P2.HourIN AND P1.HourOUT = P2.HourOUT)
于 2012-12-18T15:10:05.063 回答
0

你可以使用这样的东西:

SELECT
  t.Name, 
  t.Date, 
  t.HourIN, (
     SELECT Top 1 HourOut 
     FROM THourOUT o 
     WHERE o.Name=t.Name AND o.Date=t.date And o.HourOUT>t.HourIN 
     ORDER BY o.HourOUT,o.ID ) AS HrOut
FROM THourIN AS t
ORDER BY t.Date, t.HourIN;

请注意,我在 OUT 表中添加了一个 ID,以确保 top 1 不会返回重复项。

这是插入缺失值的示例。它取决于包含从 0 或 1 到最大缺失值数量的整数的 Numbers 表。数字表在许多方面都很有用。

INSERT INTO thourin
            (name,
             [date])
SELECT q.name,
       q.DATE
FROM   (SELECT Outs.name,
               Outs.DATE,
               Outs.countofout,
               Ins.countofin
        FROM   (SELECT o.name,
                       o.DATE,
                       Count(o.name) AS CountOfOut
                FROM   thourout o
                GROUP  BY o.name,
                          o.DATE) AS Outs
               LEFT JOIN (SELECT t.name,
                                 t.DATE,
                                 Count(t.name) AS CountOfIn
                          FROM   thourin t
                          GROUP  BY t.name,
                                    t.DATE) AS Ins
                      ON ( Outs.name = Ins.name )
                         AND ( Outs.DATE = Ins.DATE )
        WHERE  (( ( Ins.countofin ) <> [countofout]
                   OR ( Ins.countofin ) IS NULL ))) AS q,
       numbers AS n
WHERE  (( ( n.counter ) > 0
          AND ( n.counter ) <= [countofout] - [countofin] ))
于 2012-12-18T14:04:56.247 回答