Sql 左连接来自同一个表的不同查询,其中标识符的后缀递增
我有一个数据库,它有三列,在这个查询中对我来说很有趣;Id、计数器和值。Id自然是标识符,并且是唯一的。但数据库中有多个条目的初始序列中添加了一个附加后缀 每个条目对应一个不同的计数器(最多可以有三个),其值不同 数据可能是什么样子的示例Sql 左连接来自同一个表的不同查询,其中标识符的后缀递增,sql,sql-server,Sql,Sql Server,我有一个数据库,它有三列,在这个查询中对我来说很有趣;Id、计数器和值。Id自然是标识符,并且是唯一的。但数据库中有多个条目的初始序列中添加了一个附加后缀 每个条目对应一个不同的计数器(最多可以有三个),其值不同 数据可能是什么样子的示例 | id | counter | value | |--------|-------------|----------| | 1234_1 | counter_1 | 1.0 | | 1234_2 | counter_2
| id | counter | value |
|--------|-------------|----------|
| 1234_1 | counter_1 | 1.0 |
| 1234_2 | counter_2 | 7.0 |
| 1234_3 | counter_3 | 5.0 |
| 2341_1 | counter_1 | 2.0 |
| 2341_2 | counter_2 | 6.0 |
| 3412_1 | counter_1 | 8.0 |
我试图实现的是获取与ID中前4位相关的每个计数器的值。因此,如果要获取“1234”和“2341”的值,我将得到以下结果
| id | value_1 | value_2 | value_3 |
| 1234 | 1.0 | 7.0 | 5.0 |
| 2341 | 5.0 | 2.0 | NULL |
我已经为每个计数器值构建了一个使用左连接的查询,这在从一个ID检索值时可以正常工作,但在从两个不同的ID获取值时它将不起作用。然后,结果超过(在本例中)2个结果
当前查询
select LEFT(t1.id,LEN(t1.id)-1)
, t1.value
, t2.value
, t3.value
from (select * from table
where id LIKE '1234%'
AND Counter = 'counter_1') t1
left join (Select * from table Where Counter = 'counter_2') t2
on LEFT(t2.id,LEN(t2.id)-1) = LEFT(t1.id,LEN(t1.id)-1)
left join (Select * from table Where Counter = 'counter_3') t3
on LEFT(t3.id,LEN(t3.id)-1) = LEFT(t1.id,LEN(t1.id)-1)
这工作正常,将返回所需结果的第一行。但是,如果我将第一个从更改为包含另一个id
from (select * from table where id LIKE '1234%' OR [Id] LIKE '2341%' ...
它将返回四个值,其中前三个值的id为“1234”
我无法以任何方式影响数据库的结构,选择left join的原因是为了支持如果计数器的值不存在,则应为NULL
我做错了什么?我假设总是有一行t1。Counter='Counter_1':
select LEFT(t1.id,LEN(t1.id)-2), t1.value, t2.value, t3.value
from MyTable t1
left join MyTable t2 on t2.Counter = 'counter_2' and LEFT(t2.id,LEN(t2.id)-2) = LEFT(t1.id,LEN(t1.id)-2)
left join Mytable t3 on t3.Counter = 'counter_3' and LEFT(t3.id,LEN(t3.id)-2) = LEFT(t1.id,LEN(t1.id)-2)
where t1.Counter = 'counter_1'
and t1.[id] LIKE '1234%' OR t1.[Id] LIKE '2341%'
如果不是,您可以像这样欺骗查询:
select LEFT(t1.id,LEN(t1.id)-2), t1.value, t2.value, t3.value
from (select 1 as 'c') t
left join MyTable t1 on t1.Counter = 'counter_1' and t1.[id] LIKE '1234%' OR t1.[Id] LIKE '2341%'
left join MyTable t2 on t2.Counter = 'counter_2' and LEFT(t2.id,LEN(t2.id)-2) = LEFT(t1.id,LEN(t1.id)-2)
left join Mytable t3 on t3.Counter = 'counter_3' and LEFT(t3.id,LEN(t3.id)-2) = LEFT(t1.id,LEN(t1.id)-2)
你想要的是:
from (select * from [table]
where (id LIKE '1234%' OR [Id] LIKE '2341%')
AND Counter = 'counter_1') t1
因为AND是在OR之前完成的,所以你们得到的数据ID是1234%,不看计数器。我完全错过了这个。。。我知道我在之前的一个查询中注意到了它,但这次我想我错过了它。简单,简单!谢谢