How to find rows>columns combinations with Cross Join? [SQL]

强颜欢笑 提交于 2021-02-08 11:13:10

问题


I want to create a combination of items from different categories ids.

Can you help me?

table

+---------+-------------+------------+
| post_id | category_id | post_title |
+---------+-------------+------------+
| 1       | 1           | Red        |
| 2       | 1           | Black      |
| 3       | 2           | Medium     |
| 4       | 3           | Male       |
| 5       | 3           | Female     |
+---------+-------------+------------+

The query results I want is as follows:

Red-Medium-Male
Black-Medium-Male
Red-Medium-Female
Black-Medium-Female

For example, if there were items belonging to 6 different categories, it would be like below:

Red-Medium-Male-Other1-Other2-Other3

回答1:


You can use a cross join and filtering:

select t1.post_title, t2.post_title, t3.post_title
from t t1 cross join
     t t2 cross join
     t t3
where t1.category_id = 1 and
      t2.category_id = 2 and
      t3.category_id = 3;

You can generalize this using a recursive CTE:

with recursive tt as (
      select t.*, dense_rank() over (order by category_id) as cat_seqnum
      from t
     ),
     cte as (
      select cat_seqnum, post_title
      from tt
      where cat_seqnum = 1
      union all
      select  tt.cat_seqnum, concat_ws('-', cte.post_title, tt.post_title)
      from cte join
           tt
           on tt.cat_seqnum = cte.cat_seqnum + 1
     )
select *
from cte
where cat_seqnum = (select max(cat_seqnum) from tt);

Here is a db<>fiddle.



来源:https://stackoverflow.com/questions/64851724/how-to-find-rowscolumns-combinations-with-cross-join-sql

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!