回答編集履歴
1
調整
test
CHANGED
@@ -2,3 +2,47 @@
|
|
2
2
|
今のデータ形式だけでは希望する結果を導くことは難しいでしょう。
|
3
3
|
それぞれのテーブルにauto_incrementな主キー設定をして明示的に優先順位をきめられるなら
|
4
4
|
対応できるかもしれません
|
5
|
+
※SQLSERVERと文法が多少異なるかもしれませんがサンプル
|
6
|
+
```SQL
|
7
|
+
CREATE TABLE tbl1(
|
8
|
+
pid int primary key auto_increment,
|
9
|
+
id int,
|
10
|
+
kekka1 varchar(10)
|
11
|
+
);
|
12
|
+
insert into tbl1(id,kekka1) values
|
13
|
+
(1,'りんご'),
|
14
|
+
(1,'みかん'),
|
15
|
+
(2,'りんご'),
|
16
|
+
(3,'りんご'),
|
17
|
+
(3,'みかん'),
|
18
|
+
(4,'りんご');
|
19
|
+
|
20
|
+
CREATE TABLE tbl2(
|
21
|
+
pid int primary key auto_increment,
|
22
|
+
id int,
|
23
|
+
kekka2 varchar(10)
|
24
|
+
);
|
25
|
+
insert into tbl2(id,kekka2) values
|
26
|
+
(1,'2021'),
|
27
|
+
(1,'2022'),
|
28
|
+
(1,'2023'),
|
29
|
+
(1,'2024'),
|
30
|
+
(3,'2022');
|
31
|
+
|
32
|
+
select t3.id,t4.kekka1,t5.kekka2 from (
|
33
|
+
select id,(select count(*)+1 from tbl1 where id=t1.id and pid<t1.pid) as rank
|
34
|
+
from tbl1 as t1
|
35
|
+
union
|
36
|
+
select id,(select count(*)+1 from tbl2 where id=t2.id and pid<t2.pid) as rank
|
37
|
+
from tbl2 as t2
|
38
|
+
) as t3
|
39
|
+
left join (
|
40
|
+
select kekka1,id,(select count(*)+1 from tbl1 where id=t1.id and pid<t1.pid) as rank
|
41
|
+
from tbl1 as t1
|
42
|
+
) as t4 on t3.id=t4.id and t3.rank=t4.rank
|
43
|
+
left join (
|
44
|
+
select kekka2,id,(select count(*)+1 from tbl2 where id=t2.id and pid<t2.pid) as rank
|
45
|
+
from tbl2 as t2
|
46
|
+
) as t5 on t3.id=t5.id and t3.rank=t5.rank
|
47
|
+
order by t3.id,t3.rank
|
48
|
+
```
|