单行配对两行

时间:2013-05-21 00:36:38

标签: sql sql-server sql-server-2008

我有这张桌子:

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

我需要根据C(类型1和类型2)中的值对行进行配对,因为Type 1的第一条记录必须与ID的{​​{1}}匹配。 {1}}

期望的输出:

Type 2

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

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

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

3 个答案:

答案 0 :(得分:1)

你走了。对于每个“类型1”,它将找到最近的后续(按id)“类型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

答案 1 :(得分: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 Fiddle

答案 2 :(得分:-1)

试试这个

SELECT * FROM yourtable t1, yourtable t2 WHERE t1.c=t2.c