返回 SQL 中列上所有可能的值组合 [英] Return all possible combinations of values on columns in SQL

查看:12
本文介绍了返回 SQL 中列上所有可能的值组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何返回 2 列中所有值组合的列表,使它们成为 T-SQL 中的新行?

How do I return a list of all combinations of values in 2 columns so they are new rows in T-SQL?

例如

Col1, Col2
----  ----
1     2
1     4
1     5

并将其转换为所有组合:

and turn this into all combinations:

1     2
1     4
1     5
2     4
2     5
4     5

推荐答案

假设 CTE:

;with cteAllColumns as (
    select col1 as col
        from YourTable
    union
    select col2 as col
        from YourTable
)
select c1.col, c2.col 
    from cteAllColumns c1 
        cross join cteAllColumns c2 
    where c1.col < c2.col
    order by c1.col, c2.col

这篇关于返回 SQL 中列上所有可能的值组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆