简体   繁体   中英

Getting Unique Combination Of Records From One Column In SQL

My i/p is one column named Colour :-

Colour
Red
Blue 
White

I need output as :-

Red - Blue 
Red - White 
Blue - White 

How should I write SQL queries for the same considering if I need output in one column & two different columns.

You can do a self join:

DECLARE @T TABLE (Colour VARCHAR(20))
INSERT @T VALUES ('Red'), ('Blue'), ('White');

SELECT  T1.Colour, 
        t2.Colour, 
        T1.Colour + ' - ' + T2.Colour AS InOneColumn
FROM    @T AS T1
        INNER JOIN @T AS T2
            ON T2.Colour > T1.Colour;

You just need a condition to ensure that you don't get mirrored combinations, ie Blue - White and White - Blue . Using the greater than operator in the join will ensure this.

select concat(t2.colour,'-',t1.colour) from table1 t1,table1 t2 where t1.colour>t2.colour order by t2.colour,t1.colour;

替换表名,然后尝试这个。

You can use inner join & row_number window function to achieve this.

SELECT  T1.COLOR
       ,T2.COLOR
       ,T1.COLOR +' - ' + T2.COLOR 
FROM 
        (SELECT ROW_NUMBER() OVER(ORDER BY COLOR) AS RN1,COLOR FROM COLOR) T1
         JOIN 
        (SELECT (ROW_NUMBER() OVER(ORDER BY COLOR)-1) AS RN2,COLOR FROM COLOR) T2
        ON T1.RN1 = T2.RN2 OR T1.RN1+1 = T2.RN2
ORDER BY T1.COLOR       

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM