可以说,我们有这个表:
+------+------+ | COL1 | COL2 | +------+------+ | A | B | +------+------+ | B | A | +------+------+ | C | D | +------+------+
我想计算次数letter1, letter2或者letter2, letter1出现在两列中。
letter1, letter2
letter2, letter1
我想要结果:
+------+------+------+ | COL1 | COL2 | COL3 | +------+------+------+ | A | B | 2 | +------+------+------+ | C | D | 1 | +------+------+------+
注意: 它可以是AB或BA无关紧要的。
AB
BA
我试过了:
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
小提琴