Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to count the number of times two values appear in two columns in any order

Lets say, we have this table :

+------+------+
| COL1 | COL2 |
+------+------+
|   A  |   B  |
+------+------+
|   B  |   A  |
+------+------+
|   C  |   D  |
+------+------+

I want to count the number of times either letter1, letter2 or letter2, letter1 appears in the two columns.

I want the result :

+------+------+------+
| COL1 | COL2 | COL3 |
+------+------+------+
|   A  |   B  |   2  | 
+------+------+------+
|   C  |   D  |   1  |
+------+------+------+

NOTE: It can be either AB or BA doesn't matter.

I tried:

SELECT
COL1,COL1,COUNT(*) AS COL3
FROM
X
GROUP BY COL1,COL2;

But that gets me :

+------+------+------+
| COL1 | COL2 | COL3 |
+------+------+------+
|   A  |   B  |   1  |
+------+------+------+
|   B  |   A  |   1  |
+------+------+------+
|   C  |   D  |   1  |
+------+------+------+
like image 464
Hamid Y. Avatar asked Jul 01 '15 06:07

Hamid Y.


People also ask

Can I use Countif in multiple columns?

Excel COUNTIFS - things to remember!You can use the COUNTIFS function in Excel to count cells in a single range with a single condition as well as in multiple ranges with multiple conditions.

How do you count the number of occurrences in a column?

You can use the =UNIQUE() and =COUNTIF() functions to count the number of occurrences of different values in a column in Excel.


1 Answers

You can do this by swapping the columns if you need to:

SELECT Col1, Col2, COUNT(*)
FROM
(
    SELECT
        CASE WHEN Col1 < Col2 THEN Col1 ELSE Col2 END AS Col1,
        CASE WHEN Col1 < Col2 THEN Col2 ELSE Col1 END AS Col2
    FROM T
) t
GROUP BY Col1, Col2

Fiddle

like image 59
Damien_The_Unbeliever Avatar answered Oct 17 '22 02:10

Damien_The_Unbeliever