0

我有这张桌子:

A   B          C
1   Record 1   Type 1
2   Record 2   Type 2
3   Record 3   Type 1
4   Record 4   Type 2

C鉴于第一个记录Type 1必须与最接近的记录匹配,我需要按 (Type 1 & Type 2) 中的值对行进行ID配对Type 2

期望的输出:

A   B         C        A   B         C
1   Record 1  Type 1   2   Record 2  Type 2
3   Record 3  Type 1   4   Record 4  Type 2

我尝试在具有 2 个 CTE 的查询中执行此操作,但我无法得出预期的结果:

WITH SET_A (A, B, C) AS

    (SELECT * FROM A WHERE C = 'Type 1'),

SET_B (A, B, C) AS
    (SELECT * FROM A WHERE C = 'Type 2')

SELECT * FROM SET_A CROSS JOIN SET_B;   

除了使用交叉连接之外,还有其他方法吗?

4

3 回答 3

1
SELECT t1.a a1, t1.b b1, t1.c c1, t2.a a2, t2.b b2, t2.c c2
FROM Table1 t1 
JOIN Table1 t2 ON t1.c = 'Type 1' AND  t2.c = 'Type 2' AND t1.a < t2.a
WHERE t2.a  = (SELECT MIN(t3.a) FROM Table1 t3 WHERE t3.c = 'Type 2' AND t3.a > t1.a)

SQL小提琴

于 2013-05-21T01:31:36.097 回答
1

干得好。对于每个“Type 1”,它将找到最近的后续(按 id)“Type 2”。

http://sqlfiddle.com/#!6/a5263/20

CREATE TABLE t 
(
  A int,
  B varchar(32),
  C varchar(32)
  );



insert into t values (1, 'Record 1', 'Type 1')
insert into t values (2, 'Record 2', 'Type 2')
insert into t values (3, 'Record 3', 'Type 1')
insert into t values (4, 'Record 4', 'Type 2')
insert into t values (5, 'Record 5', 'Type 1')
insert into t values (6, 'Record 6', 'Type 1a')
insert into t values (7, 'Record 7', 'Type 2')


;

with set_a as 
(
  select * from t where c = 'type 1'
)
, set_b as 
(
  select a, b, c, a_match = (select max(t2.a) from t t2 where t2.a < t.a and t2.c = 'type 1') 
  from t where c = 'type 2'
)
select set_a.* , a2 = set_b.a, b2 = set_b.b, c2 = set_b.c
from set_a
join set_b on set_b.a_match = set_a.a
于 2013-05-21T01:11:16.367 回答
-1

试试这个

SELECT * FROM yourtable t1, yourtable t2 WHERE t1.c=t2.c
于 2013-05-21T00:46:18.677 回答