我有一张这样的表:
index|from | to
------------------
1 | ABC | DEF
2 | ABC | GHI
3 | ABC | GHI
4 | ABC | JKL
5 | ABC | JKL
6 | ABC | JKL
7 | DEF | ABC
8 | DEF | GHI
9 | DEF | JKL
10 | GHI | ABC
11 | GHI | ABC
12 | GHI | ABC
13 | JKL | DEF
我需要计算点之间的总时间(不论方向)如何得到结果:
A | B | count
-----------------
ABC | DEF | 2
ABC | GHI | 5
ABC | JKL | 3
DEF | GHI | 1
DEF | JKL | 2
到目前为止,我可以得到:
SELECT `a`.`from` as `A`, `a`.`to` as `B`, (`a`.`count` + `b`.`count`) as `count`
FROM
(SELECT `from`, `to`, count(*) as `count`
FROM `table`
GROUP BY 1,2) `a`
LEFT OUTER JOIN
(SELECT `from`,`to`, count(*) as `count`
FROM `table`
GROUP BY 1,2) `b`
ON `a`.`from` = `b`.`to`
AND `a`.`to` = `b`.`from`
但我不确定如何删除A / B交换重复项。
答案 0 :(得分:0)
SELECT 'from' as first, 'to' as second
FROM 'table'
UNION
SELECT 'to' as first, 'from' as second
FROM 'table'
这会给你所有的对,前进和后退。要消除重复项,您只需要一个在第一个和第二个上强加顺序的WHERE子句。
SELECT first, second, count(*)
FROM (
SELECT 'from' as first, 'to' as second
FROM 'table'
UNION
SELECT 'to' as first, 'from' as second
FROM 'table'
) x
WHERE first < second
GROUP BY first, second
避免使用字段和表名称的关键字会更简单;你可以不用引号。
答案 1 :(得分:0)
select `from` as A, `to` as B, count(*) as `count`
from your_table
group by if (from<to, concat(from,to), concat(to,from));