我知道SQL的基础知识但不过是初学者,所以我不知道如何以正确的方式搜索这个问题。
问题: 如何在两列设置中计算匹配关系?示例:
我用:
SELECT "from", "to", COUNT(*) Count
FROM "LocationDestination"
GROUP BY "from", "to"
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC
让我:
from to Count
Germany USA 6
USA Spain 5
Marocco Spain 4
USA Germany 2
Spain Marocco 2
我想要的是一个看起来像这样的表:
Destination1 Destionation2 Count
Germany USA 8
Marocco Spain 6
USA Spain 5
因此将德国 - 美国与美国 - 德国,摩洛哥 - 西班牙与西班牙 - 摩洛哥之类的旅行结合起来......等等。
如何实现?
答案 0 :(得分:2)
MySQL - 如果存在对称对,则使用least
和greatest
只能获得一个组合。
SELECT least("from", "to"), greatest("from", "to"), COUNT(*) Count
FROM "LocationDestination"
GROUP BY least("from", "to"), greatest("from", "to")
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC
答案 1 :(得分:0)
这是另一种方式
SELECT case when froms > tos then froms else tos end,
case when froms < tos then froms else tos end,
Count(*)
FROM Yourtable
GROUP BY case when froms > tos then froms else tos end,
case when froms < tos then froms else tos end