如何返回2列中所有值組合的列表,使它們成爲T-SQL中的新行?返回SQL列中值的所有可能組合
例如
Col1, Col2
---- ----
1 2
1 4
1 5
,並把它變成所有組合:
1 2
1 4
1 5
2 4
2 5
4 5
如何返回2列中所有值組合的列表,使它們成爲T-SQL中的新行?返回SQL列中值的所有可能組合
例如
Col1, Col2
---- ----
1 2
1 4
1 5
,並把它變成所有組合:
1 2
1 4
1 5
2 4
2 5
4 5
假設至少是SQL 2005年爲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
你可以做一個自交加入...
SELECT a.Col1, b.Col2
FROM MyTable a
CROSS JOIN MyTable b
爲什麼這個答案更受歡迎?有什麼不對? – 2015-06-29 21:00:09
我想這需要`SELECT DISTINCT`。此外,雖然這很有用,但它不會做OP所要的,它是* both *列的所有組合! – LondonRob 2015-07-16 12:29:57
你可以笛卡兒連接的表本身,這將返回兩列的所有組合。
select
distinct
t1.Col1,
t2.Col2
from
MyTable t1,
MyTable t2
添加「選擇不同」,你已經得到它。 – 2010-12-07 16:15:46
我試過這個,但是我需要Col 1中的Col 2值,所以它們被交換。我認爲unpivot可能會幫助,但不是很確定... – jaffa 2010-12-07 16:16:42
這將使用2的CTE,首先簡單地再現您的輸入表,第二個變成兩列成一列。最終選擇交叉連接的這一套來自己生產所需的輸出
with t(c1,c2)
AS
(
select 1,2
union select 1,4
union select 1,5
)
,t2(c)
as
(
select c1 from t
union select c2 from t
)
select t2_1.c, t2_2.c
from t2 t2_1
cross join t2 t2_2
where t2_1.c<t2_2.c
order by t2_1.c
我發現內部連接更直觀,因爲我用它的頻率比交叉聯接:
;with cteAllColumns as (
select col1 as col
from YourTable
union
select col2 as col
from YourTable
)
select c1.col, c2.col
from cteAllColumns c1
join cteAllColumns c2 on 1=1
where c1.col < c2.col
order by c1.col, c2.col
使喬答容易
declare @t1 table (col1 varchar(5))
insert @t1
select 'A' UNION
select 'B' UNION
select 'C'
declare @t2 table (col2 varchar(5))
insert @t2
select '1' UNION
select '2' UNION
select '3'
;with cteAllColumns as (
select col1 as col
from @t1
union
select col2 as col
from @t2
)
select c1.col, c2.col
from cteAllColumns c1
cross join cteAllColumns c2
where c1.col < c2.col
order by c1.col, c2.col
驗證您的組合數量(無行) http://www.calculatorsoup.com/calculators/discretemathematics/combinations.php
我認爲這已經過於複雜了!
剛:
SELECT distinct Col1, Col2
FROM MyTable
得到所有可能的組合..
我一直在尋找的東西,會使用只適用到Microsoft Access 2016年我最終搞清楚東西SQL做到這一點別人可能會覺得有用。此代碼使用CROSS JOIN,因此我發現有必要將兩列分成兩個單獨的表(每列都有一列)。 AND語句強制一列小於另一列,從而消除任何重複的1-2次,2-1次事件。
SELECT DISTINCT Table1.Column1, Table2.Column1
FROM Table1, Table2
WHERE Table1.Column1 <> Table2.Column1
AND Table2.Column1 < Table1.Column1;
你是什麼意思的「新行」?什麼是組合的規則? '1,1'是否有效? – Oded 2010-12-07 16:04:44
3個原始行位於一個表內,需要使用select語句擴展它們。 – jaffa 2010-12-07 16:14:46