How to make SQL query to sort data of the same kind from two column in a table and select from the query.

Emeka Okoye 46 Reputation points
2021-10-21T05:11:05.433+00:00

hello,

I have a table that has two column that contain similar data, but I want to check the two column col1 and col2, if the number of data in col1 is equal to number of data col2, make a temp list of col1 data that has lesser number of data in col2.
my table is like this.

col1 || col2
0001 || 0001
0002 || 0001
0003 || 0002
0004 || 0002
0005 || 0003
0006 || 0004
0007 || 0005


so I want to check col1 against col2, any data in col2 that is less than 2 will be listed on a temp list, from the temp list I will like to select any number of row.

Please anyone with Idea on how I can solve this.
Thanks.

Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,560 questions
{count} votes

Accepted answer
  1. EchoLiu-MSFT 14,571 Reputation points
    2021-10-26T03:09:13.21+00:00

    Please also try:

    ;WITH cte as(SELECT DISTINCT col2,COUNT(col2) OVER(PARTITION BY col2) cc
                 FROM #test)
    
    SELECT t.col1,t.col2,
    CASE WHEN cc>=2 THEN NULL ELSE t.col1 END temp
    FROM #test t
    LEFT JOIN cte c ON t.col1=c.col2
    

    Regards
    Echo


5 additional answers

Sort by: Most helpful
  1. Viorel 112.9K Reputation points
    2021-10-25T09:26:46.69+00:00

    For your additional explanation, try this query:

    select col1, col2,
         case when (select count(*) from  #test where col2 = t.col1) < 2 then col1 end as temp
    from #test t
    
    0 comments No comments