我有两个表(A和B),其中我想要选择满足条件的两行:
if a.time and b.time <= 12 hours
AND A.col1 = B.col2 AND A.col2 = B.col1
A
|Date | Time | Col1 | Col2
|20150818| 000256| AAAA | BBBB
|20150818| 000456| AAAA | CCCC
乙
|Date | Time | Col1 | Col2
|20150820| 000359| BBBB | AAAA
|20150818| 000259| BBBB | AAAA
|20150818| 001459| CCCC | AAAA
预期输出
|Date | Time | Col1 | Col2 |Date | Time | Col1 | Col2
|20150818| 000256| AAAA | BBBB |20150818| 000259| BBBB | AAAA
|20150818| 000456| AAAA | CCCC |20150818| 001459| CCCC | AAAA
因为我是SQL新手,
select *
from A
where exists
(select 1 from B where B.Col1 = A.Col2 and B.Col2 = A.Col1)
仅显示表A中的行而不考虑时间。
答案 0 :(得分:1)
为了将一个表的记录与另一个表的记录组合在一起,您加入表:
当您将日期和时间存储为字符串时,必须先将它们转换为DATE(即日期时间值)。然后从另一个中减去一个,以便得到天数的差异。 12小时= 0.5天。
select
a.date, a.time, a.col1, a.col2,
b.date, b.time, b.col1, b.col2
from a
join b on a.col1 = b.col2 and a.col2 = b.col1
and abs(to_date(a.date || a.time , 'yyyymmddhh24miss') -
to_date(b.date || b.time , 'yyyymmddhh24miss')) <= 0.5;
将日期和时间存储在两个单独的varchar列中的方式并不常见。通常,您只需使用包含日期和时间的DATE列。
答案 1 :(得分:1)
Oracle 11g R2架构设置:
CREATE TABLE A ( "Date", "Time", Col1, Col2 ) AS
SELECT '20150818', '000256', 'AAAA', 'BBBB' FROM DUAL
UNION ALL SELECT '20150818', '000456', 'AAAA', 'CCCC' FROM DUAL;
CREATE TABLE B ( "Date", "Time", Col1, Col2 ) AS
SELECT '20150820', '000359', 'BBBB', 'AAAA' FROM DUAL
UNION ALL SELECT '20150818', '000259', 'BBBB', 'AAAA' FROM DUAL
UNION ALL SELECT '20150818', '001459', 'CCCC', 'AAAA' FROM DUAL;
查询1 :
SELECT *
FROM A
INNER JOIN
B
ON (
TO_DATE( a."Date" || a."Time", 'YYYYMMDDHH24MISS' ) BETWEEN TO_DATE( b."Date" || b."Time", 'YYYYMMDDHH24MISS' ) - INTERVAL '12' HOUR AND TO_DATE( b."Date" || b."Time", 'YYYYMMDDHH24MISS' ) + INTERVAL '12' HOUR
AND a.Col1 = b.Col2
AND a.Col2 = b.Col1
)
<强> Results 强>:
| Date | Time | COL1 | COL2 | Date | Time | COL1 | COL2 |
|----------|--------|------|------|----------|--------|------|------|
| 20150818 | 000256 | AAAA | BBBB | 20150818 | 000259 | BBBB | AAAA |
| 20150818 | 000456 | AAAA | CCCC | 20150818 | 001459 | CCCC | AAAA |
答案 2 :(得分:0)
试试这个
select * from A inner join (select * from B where b.time <= 12 hours) C
on C.Col1 = A.Col2 and C.Col2 = A.Col1