我有2个表(THour_IN和THour_OUT)具有相同的模式: THour_IN的列:名称|日期| HourIN Colour for THULL_OUT:名称|日期|小时 我查询:
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)与Fisrt HourOUT(16:36:06),Second HourIN(17:33:06)with Second HourOUT(20:33: 06)有什么想法吗?
答案 0 :(得分: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)
答案 1 :(得分: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不会返回重复项。
以下是插入缺失值的示例。它取决于一个Numbers表,其中包含从0或1到最大缺失值的整数。数字表在很多方面都很有用。
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] ))