CREATE TABLE tmp
(
id INT,
ksrq VARCHAR(8),
jsrq VARCHAR(8)
)
INSERT INTO dbo.TMP
SELECT 1,'20130101','20130101'
INSERT INTO dbo.TMP
SELECT 2,'20130102','20130105'
INSERT INTO dbo.TMP
SELECT 3,'20130105','20130105'
INSERT INTO dbo.TMP
SELECT 4,'20130103','20130103'
INSERT INTO dbo.TMP
SELECT 5,'20130106','20130106'
有如上结构的表,想查询出日期有重叠的id.求解答.
(例子中2、3、4是有重叠的).
非常感谢 @幻天芒 的帮助,列出最后语句.
SELECT DISTINCT id
FROM
(
SELECT DISTINCT t1.Id
FROM tmp t1
LEFT JOIN tmp t2
ON t1.id <> t2.id
AND t2.ksrq >= t1.ksrq
AND t2.jsrq <= t1.jsrq
WHERE t2.id IS NOT NULL
UNION ALL
SELECT DISTINCT t2.Id
FROM tmp t1
LEFT JOIN tmp t2
ON t1.id <> t2.id
AND t2.ksrq >= t1.ksrq
AND t2.jsrq <= t1.jsrq
WHERE t2.id IS NOT NULL
) AS AA
提问的方式挺好。不过最后日期重叠的规则是啥???
@tian_z: 原来是时间段重复啊~
@幻天芒: 是啊,好像挺复杂的样子。
SELECT * FROM #tmp t1 LEFT JOIN #tmp t2 ON t1.id<>t2.id AND t2.ksrq>=t1.ksrq AND t2.jsrq<=t1.jsrq
你看看呢~嘿嘿~
@tian_z:
@幻天芒: 好像不行,<=and>=这样会查询出所有的记录的
@tian_z: ...还需要处理下啊~~~!!!
SELECT DISTINCT t1.Id FROM #tmp t1 LEFT JOIN #tmp t2 ON t1.id <> t2.id AND t2.ksrq >= t1.ksrq AND t2.jsrq <= t1.jsrq WHERE t2.id IS NOT NULL UNION ALL SELECT t2.Id FROM #tmp t1 LEFT JOIN #tmp t2 ON t1.id <> t2.id AND t2.ksrq >= t1.ksrq AND t2.jsrq <= t1.jsrq WHERE t2.id IS NOT NULL
写完给你了~