gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 23:58:09 28 4
gpt4 key购买 nike

比方说,我们有这张 table :

+------+------+
| 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 |
+------+------+------+

最佳答案

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

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

关于mysql - 如何计算两个值以任意顺序出现在两列中的次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31154204/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com