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

时间:2015-07-01 06:41:05

标签: mysql sql database count

让我们说,我们有这张表:

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

我想计算letter1, letter2letter2, 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  |
+------+------+------+

4 个答案:

答案 0 :(得分:15)

如果需要,可以通过交换列来执行此操作:

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

答案 1 :(得分:3)

另一次尝试

SELECT LEAST(col1, col2) col11, GREATEST(col1, col2) col12 , COUNT(1) FROM X
GROUP BY col11, col12

SqlFiddle

答案 2 :(得分:0)

  

更新:使用@Damien的答案。另一种尝试。

您可以尝试以下代码。 Fiddle

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

答案 3 :(得分:-1)

请参阅http://sqlfiddle.com/#!9/4bd6a/23

使用if语句并连接2列。

SELECT
  DISTINCT (CONCAT(C1,C2)) AS permutation, COUNT(1)
  FROM (SELECT
    IF(col1<=col2, col1, col2) as C1,
    IF(col2<col1, col1, col2) as C2
  FROM X) AS T
  GROUP BY permutation
;

进一步说明: if语句只是按ASCII值对字符进行排序,因此无论&#39; AB&#39;或者&#39; BA&#39;,它将始终表示为&#39; AB&#39;