小编典典

如何计算两个值以任意顺序出现在两列中的次数

sql

可以说,我们有这个表:

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

我想计算次数letter1, letter2或者letter2, letter1出现在两列中。

我想要结果:

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

注意: 它可以是ABBA无关紧要的。

我试过了:

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

但这让我:

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

阅读 151

收藏
2021-05-16

共1个答案

小编典典

如果需要,您可以通过交换列来做到这一点:

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

小提琴

2021-05-16