获取保存在多行中的相应代码
fetch corresponding codes saved in mulitple rows
以下table、table_a包含ID、代码及对应值:
编号
代码
值
1
代码1
12
1
code2
10
1
code3
09
1
code4
89
1
code5
71
2
代码1
12
2
code2
96
2
code3
58
2
code4
74
下面 table,table_b 包含对应的 vat_number id。
编号
vat_number
1
58965
2
56974
我只需要获取 ID、vatnumber 以及 code1 和 code2。
最终输出应如下所示:
编号
vat_number
代码1
code2
1
58965
12
10
2
56974
12
96
目前我正在使用以下查询获取数据,但我相信一定有更好的方法来获取此类信息。我正在使用 Oracle 11g。
select b.id, b.vat_number, a.value,c.value
from table_a a, table_b b, table_a c
where a.id=b.id and b.id=c.id
and a.code='code1' and c.code='code2'
你的方法没问题,但你应该使用正确的、明确的、标准、可读的JOIN
语法:
select b.id, b.vat_number, a1.value, a2.value
from table_b b join
table_a a1
on a1.id = b.id and a1.code = 'code1' join
table_a a2
on a2.id = b.id and a2.code = 'code2';
您也可以使用条件聚合
select b.id, b.vat_number,
max(case when a.code = 'code1' then a.value end),
max(case when a.code = 'code2' then a.value end)
from table_b b join
table_a a
on a.id = b.id
where a.code in ('code1', 'code2')
group by b.id, b.vat_number;
您可以 运行 进行测试,看看哪个在您的数据上速度更快。
以下table、table_a包含ID、代码及对应值:
编号 | 代码 | 值 |
---|---|---|
1 | 代码1 | 12 |
1 | code2 | 10 |
1 | code3 | 09 |
1 | code4 | 89 |
1 | code5 | 71 |
2 | 代码1 | 12 |
2 | code2 | 96 |
2 | code3 | 58 |
2 | code4 | 74 |
下面 table,table_b 包含对应的 vat_number id。
编号 | vat_number |
---|---|
1 | 58965 |
2 | 56974 |
我只需要获取 ID、vatnumber 以及 code1 和 code2。
最终输出应如下所示:
编号 | vat_number | 代码1 | code2 |
---|---|---|---|
1 | 58965 | 12 | 10 |
2 | 56974 | 12 | 96 |
目前我正在使用以下查询获取数据,但我相信一定有更好的方法来获取此类信息。我正在使用 Oracle 11g。
select b.id, b.vat_number, a.value,c.value
from table_a a, table_b b, table_a c
where a.id=b.id and b.id=c.id
and a.code='code1' and c.code='code2'
你的方法没问题,但你应该使用正确的、明确的、标准、可读的JOIN
语法:
select b.id, b.vat_number, a1.value, a2.value
from table_b b join
table_a a1
on a1.id = b.id and a1.code = 'code1' join
table_a a2
on a2.id = b.id and a2.code = 'code2';
您也可以使用条件聚合
select b.id, b.vat_number,
max(case when a.code = 'code1' then a.value end),
max(case when a.code = 'code2' then a.value end)
from table_b b join
table_a a
on a.id = b.id
where a.code in ('code1', 'code2')
group by b.id, b.vat_number;
您可以 运行 进行测试,看看哪个在您的数据上速度更快。