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 |
+------+------+------+
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.
You can use the =UNIQUE() and =COUNTIF() functions to count the number of occurrences of different values in a column in Excel.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With