我有以下现有表格(简化版本),我必须从中创建结果表格。我知道我必须做一些复杂的自联接才能到达结果表,但是无法让它工作。我唯一的另一种选择是编写程序或PL / SQL程序,如果可能的话我想避免这种程序。
PId From To Timestamp field
1 1 2 8/09/2014
2 1 2 8/09/2014
3 1 3 8/09/2014
4 1 3 8/09/2014
5 1 3 8/09/2014
6 2 3 8/09/2014
7 2 3 8/09/2014
8 2 4 8/09/2014
9 2 4 8/09/2014
10 3 1 8/09/2014
11 1 3 8/08/2014
12 2 3 8/08/2014
13 2 3 8/08/2014
14 3 2 8/08/2014
要求是在前向(Outgoing)和反向(Incoming)方向上计算具有From-To组合的行数。将以查询的形式大大欣赏解决方案。请注意,最后2列还包括我在paranthesis中的注释,在预期值旁边。这是为了更好地理解需求。
结果表:
DaysOld A B Outgoing(Comments) Incoming (Comments)
1 1 2 2(PId: 1,2) 0
1 2 1 0 2(PId: 1,2)
1 1 3 3(PId: 3,4,5) 1(PId: 10)
1 3 1 1(PId: 10) 3(PId: 3,4,5)
1 2 3 2 0
1 3 2 0 2
1 2 4 2 0
1 4 2 0 2
2 1 3 1 0
2 3 1 0 1
2 2 3 2 1
2 3 2 1 2
答案 0 :(得分:0)
除非它不包含冗余行,否则应该执行您之后的操作。可以通过与最大和最小的查询进行联合来添加它们。
SELECT LEAST(From,To) AS A, GREATEST(From,To) AS B,
SUM(CASE WHEN FROM < TO THEN 1 ELSE 0 END) AS Outgoing
SUM(CASE WHEN FROM > TO THEN 1 ELSE 0 END) AS Incoming
FROM table1
GROUP BY LEAST(From,To), GREATEST(From,To)
我还假设From和To不能相等。
只是要完成,包含冗余行的查询:
SELECT LEAST(From,To) AS A, GREATEST(From,To) AS B,
SUM(CASE WHEN FROM < TO THEN 1 ELSE 0 END) AS Outgoing
SUM(CASE WHEN FROM > TO THEN 1 ELSE 0 END) AS Incoming
FROM table1
GROUP BY LEAST(From,To), GREATEST(From,To)
UNION
SELECT GREATEST(From,To) AS A, LEAST(From,To) AS B,
SUM(CASE WHEN TO < FROM THEN 1 ELSE 0 END) AS Outgoing
SUM(CASE WHEN TO > FROM THEN 1 ELSE 0 END) AS Incoming
FROM table1
GROUP BY GREATEST(From,To), LEAST(From,To)