mssql-基于另一个列值并排显示列

t5fffqht  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(234)

我有一张table,上面有类似的行

+-----+-------+---------------+
|  id | time  | linked init id|
+-----+-------+---------------+    
|  1  + 10.00 |     0         |
+-----+-------+---------------+    
|  2  + 11.00 |     0         |
+-----+-------+---------------+
|  3  + 15.00 |     1         |
+-----+-------+---------------+ 
|  4  + 10.00 |     0         |
+-----+-------+---------------+ 
|  5  + 15.30 |     2         |
+-----+-------+---------------+

我想根据与“id”匹配的“linked init id”查询并排显示时间字段
例句:结果应该是这样的

+-----+-------+-------+
|  id | time1 | time2 |
+-----+-------+-------+   
|  1  | 10.00 | 15.00 |  //because id value "1" = linked init id value "1"
+-----+-------+-------+
|  2  | 11.00 | 15.00 |  //because id value "2" = linked init id value "2"
+-----+-------+-------+

我该怎么做?
注意:每个id只能有0或1个链接id行

hvvq6cgz

hvvq6cgz1#

您需要将表与其自身连接起来:

SELECT time1.id, time1.time AS time1, time2.time as time2
FROM Table time1
JOIN Table time2 ON time2.[linked init id] = time1.id
djmepvbi

djmepvbi2#

你可以试试下面这个脚本-
此处演示

SELECT A.linked_init_id, B.time Time1,A.Time Time2 
FROM your_table A
INNER JOIN your_table B ON A.linked_init_id = B.id
WHERE A.linked_init_id <> 0

相关问题