Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch single row if two columns in table have same values either ways

Tags:

sql

sql-server

I have a table with columns caller and callee with following values say

caller callee
999 888
888 999
999 555
555 333
555 999

now i want only single row in returned as

caller1    caller2  count 
999        888      2
999        555      1
555        333      1
555        999      2
like image 466
Rajeev Kumar Avatar asked Oct 12 '12 13:10

Rajeev Kumar


People also ask

How do I compare two columns in the same table?

Comparison of columns in the same table is possible with the help of joins. Here we are comparing all the customers that are in the same city using the self join in SQL. Self-join is a regular join where a table is joined by itself. Similarly, a table may be joined with left join, right join, inner join, and full join.

How do I check if two columns have the same value in mysql?

Find duplicate values in multiple columns In this case, you can use the following query: SELECT col1, COUNT(col1), col2, COUNT(col2), ... FROM table_name GROUP BY col1, col2, ... HAVING (COUNT(col1) > 1) AND (COUNT(col2) > 1) AND ...

Can we use multiple columns in where clause?

If you want compare two or more columns. you must write a compound WHERE clause using logical operators Multiple-column subqueries enable you to combine duplicate WHERE conditions into a single WHERE clause.


1 Answers

SELECT CASE
         WHEN caller < callee THEN callee
         ELSE caller
       END      AS caller1,
       CASE
         WHEN caller < callee THEN caller
         ELSE callee
       END      AS caller2,
       Count(*) AS [Count]
FROM   YourTable
GROUP  BY CASE
            WHEN caller < callee THEN callee
            ELSE caller
          END,
          CASE
            WHEN caller < callee THEN caller
            ELSE callee
          END 
like image 153
Martin Smith Avatar answered Oct 18 '22 01:10

Martin Smith