我试图连接两个表,但只考虑表1中的部分字符串。
我有表_1,它看起来就像这样:
product date_creation
door 2020-01-02
car 2020-02-10
house/big 2020-03-15
表2:
product amount
door/brown 10
door 100
car/toyota 5
car/toyota/black 15
house/big/beach 3
house/big/beach/old 2
我想得到这个结果:
product date_creation amount
door 2020-01-02 110
car 2020-02-10 20
house/big 2020-03-15 5
所以我想加入所有可能的子字符串的表。
我知道我可以做一些类似的事情:
select t1.*, sum(t2.amount)
from table_1 t1
left join table_2 t2
on t1.product = split_part(t2.product, '/', 1)
group by 1,2
如果everithing就像门和车。然而,由于house/big,我一直没有解决方案。
like
应该这样做:
select t1.*, sum(t2.amount)
from table_1 t1
left join table_2 t2 on t2.product like t1.product || '/%'
group by t.product
这确保了";"长";来自CCD_ 2的产物以开始;短";来自t1
的乘积,后面跟一个斜线。
如果完美匹配是可能的,那么以下更安全:
select t1.*, sum(t2.amount)
from table_1 t1
left join table_2 t2 on t2.product || '/' like t1.product || '/%'
group by t.product
我对group by
子句不太满意(位置表达式和select *
不能很好地结合在一起(。我将其更改为t.product
,我认为它是t1
的主键。