如何循环遍历 postgresql 中的查询选择?

问题描述 投票:0回答:1

这是我在 postgresql 中的代码,它工作得很好:

select 
    case 
        when cfd.value like '%TryUSI%' then 'TryUSI'
        when cfd.value like '%Workshop%' then 'Workshop'
        when cfd.value like '%KOOP%' then 'KOOP'
        when cfd.value like '%dual%' then 'dual'
        when cfd.value like '%NEU%' then 'Neu'
        else 'kein Tag'
    end as Tag, count(bo.id)
from mdl_booking_options bo
join mdl_customfield_data cfd on cfd.instanceid = bo.id  and cfd.fieldid = 5
where bo.bookingid = 17
group by Tag;

但我希望我的代码更通用。比如:

DEFINE $variable = 'SELECT botags from table2'
select 
    case 
        when cfd.value like '%$variable%' then variable
        else 'kein Tag'
    end as Tag, count(bo.id)
from mdl_booking_options bo
join mdl_customfield_data cfd on cfd.instanceid = bo.id  and cfd.fieldid = 5
where bo.bookingid = 17
group by Tag;

有人知道如何让伪代码工作吗?

postgresql
1个回答
0
投票

SQL 中没有循环,但您可以通过子查询来实现这一点:

select 
    coalesce((
        select botags
        from table2
        where cfd.value like '%' || botags || '%'
        -- order by ???
        limit 1
    ), 'kein Tag') as Tag, count(bo.id)
from mdl_booking_options bo
join mdl_customfield_data cfd on cfd.instanceid = bo.id  and cfd.fieldid = 5
where bo.bookingid = 17
group by Tag;
© www.soinside.com 2019 - 2024. All rights reserved.