首页 新闻 会员 周边 捐助

问个SQL问题,求解答

0
悬赏园豆:80 [已解决问题] 解决于 2013-09-09 21:50

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的主页 tian_z | 初学一级 | 园豆:158
提问于:2013-09-09 19:30
< >
分享
最佳答案
0

提问的方式挺好。不过最后日期重叠的规则是啥???

收获园豆:80
幻天芒 | 高人七级 |园豆:37207 | 2013-09-09 21:12
 20130102-20130105 包含了 20130105 和 20130103 所以算有重叠 ,只要是2列的时间段有一天是重复的就算重复。
tian_z | 园豆:158 (初学一级) | 2013-09-09 21:13

@tian_z: 原来是时间段重复啊~

幻天芒 | 园豆:37207 (高人七级) | 2013-09-09 21:22

@幻天芒: 是啊,好像挺复杂的样子。

tian_z | 园豆:158 (初学一级) | 2013-09-09 21:25
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: 

幻天芒 | 园豆:37207 (高人七级) | 2013-09-09 21:27

@幻天芒: 好像不行,<=and>=这样会查询出所有的记录的

tian_z | 园豆:158 (初学一级) | 2013-09-09 21:33

@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

写完给你了~

幻天芒 | 园豆:37207 (高人七级) | 2013-09-09 21:36
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册