[英]How to extract multiple rows from a table based on values from multiple columns from another table and then concatenate in SQL?
我有两个表,表 1 和表 2。表 1 有“开始”和“结束”列。 表 2 具有列“位置”和“序列”。 我想从表 2 中提取序列,从 position = start 到 position = end 并使用连接字符串创建一个新列。
表格1
开始 | 结尾 |
---|---|
100 | 104 |
105 | 109 |
表 2
Position | 序列 |
---|---|
100 | 一个 |
101 | 吨 |
102 | C |
103 | 吨 |
104 | G |
105 | 吨 |
106 | 吨 |
107 | G |
108 | 吨 |
109 | G |
我的最终结果需要是
开始 | 结尾 | 序列 |
---|---|---|
100 | 104 | ATCTG |
105 | 109 | TTGTG |
我尝试使用以下语句连接表 2 中的值
SELECT Sequence = (Select '' + Seq
from Table2
where Position >= 100 and Position <= 104
order by Position FOR XML PATH('')
)
您没有 state 您正在使用什么 DBMS,所以这里是一个 SQL 服务器解决方案,使用 CTE 和 FOR XML 来执行转置:
; WITH SequenceCTE AS
(
SELECT [Start],
[End],
Seq
FROM Table1 a
JOIN Table2 b
ON b.Position >= a.[Start] AND
b.Position <= a.[End]
)
SELECT DISTINCT
a.[Start],
a.[End],
(
SELECT STUFF(',' + Seq,1,1,'')
FROM SequenceCTE b
WHERE a.[Start] = b.[Start] AND
a.[End] = b.[end]
FOR XML PATH ('')
)
FROM SequenceCTE a
在标准 SQL 中,您可以执行以下操作:
select t1.start, t1.end,
listagg(t2.position, '') within group (order by t2.seq) as sequence
from table1 t1 join
table2 t2
on t2.position between t1.start and t2.end
group by t1.start, t1.end;
大多数数据库支持聚合字符串连接,但 function 可能有不同的名称和略有不同的语法。
请注意, start
和end
是列的糟糕名称,因为它们是 SQL 关键字 - 大多数数据库中的sequence
也是如此。
您可以为您的第一个表生成行号,稍后可用于在加入这些数字后对范围进行分组:
with to_id as (select row_number(*) over (order by t1.start) id, t1.* from table1 t1),
ranges as (select t3.id, t2.* from table2 t2 join to_id t3 on t3.start <= t2.position and t2.position <= t3.end)
select t3.start, t3.end, group_concat(r1.seq, '') from ranges r1 join to_id t3 on r1.id = t3.id group by r1.id;
查看交叉表查询是如何完成的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.