假设我们拥有标题,职位和来源的产品。
http://rextester.com/live/TCFOBJ26312
我需要按字符串模式“basse”订购产品。 订购产品后应如下:
id title source position
9 prod 9 b 0
1 prod 1 a 0
13 prod 13 s 0
14 prod 14 s 1
5 prod 5 e 0
10 prod 10 b 1
2 prod 2 a 1
15 prod 15 s 2
16 prod 16 s 3
6 prod 6 e 1
11 prod 11 b 2
3 prod 3 a 2
7 prod 7 e 2
12 prod 12 b 3
4 prod 4 a 3
8 prod 8 e 3
答案 0 :(得分:1)
select id, title, source, position
from (
select id, title, source, position, new_source,
case new_source
when 'b' then 0
when 'a' then 1
when 's' then 2
when 't' then 3
else 4
end as pos
from (
select id, title, source, position,
case
when source <> 's' then source
when (row_number() over w % 2)::int::bool then 's'
else 't'
end as new_source
from products
window w as (partition by source order by position)
) s
) s
window w as (partition by new_source order by position)
order by (row_number() over w)* 5+ pos;
答案 1 :(得分:0)
您只能通过排序来实现这一目标。相反,创建一个PL / pgSQL函数“basse()”,它返回一组setof记录。 在函数内部,为b,a,s,e声明四个未绑定的产品%rowtype数组,并打开游标迭代产品。 将每个读取的产品放在相应的数组中。 然后插入数组,从正确的数组返回一个元素(如果不是空的话)。最后在函数结束时调用RETURN。 要使用该功能,请执行SELECT * FROM basse()