选择跨表格,不包括已连接表格的第一行和最后一行

时间:2014-03-19 09:57:17

标签: mysql sql join

有两个表 Session View ,其中一个会话可能包含许多视图:

Session    
id | app | other_columns
------------------
1  | A   | text
2  | A   | text

View    
id | session | name |   start    |     end
---------------------------------------------
1  | 1       | A    | 1395221810 | 1395221836
2  | 1       | B    | 1395221837 | 1395221945
3  | 1       | A    | 1395221846 | 1395221998
4  | 2       | A    | 1392241521 | 1392241563
5  | 2       | G    | 1392241564 | 1392241565
6  | 2       | F    | 1392241566 | 1392241579
7  | 2       | I    | 1392241580 | 1392241596
8  | 2       | J    | 1392241596 | 1392241612

现在我想得到所有会话的平均长度(根据属于会话的每个视图的 end - start 的总和计算),其中app = 'A',不包括每个会话的第一个和最后一个视图(即行)。在上面的示例中,应从计算中排除视图1 + 3(属于会话1)和4 + 8(会话2)。

我开始时的陈述看起来像这样,但显然,它没有包含第一行+最后一行 - 排除:

SELECT 
    AVG(v.end - v.start)
FROM
    View AS v
        JOIN
    Session AS s ON s.ID = v.session
WHERE
    s.app = 'A';

1 个答案:

答案 0 :(得分:2)

select max(id) as max_id, min(id) as min_id, session
from view
group by sesion;

id被排除在外。

select * 
from view
     left join (select max(id) as max_id, min(id) as min_id, session
                from view
                group by sesion) exclude ON view.session=exclude.session 
                     AND (view.id=exclude.min_id or view.id=exclude.max_id)
having exclude.session is null;

查看没有排除ID的数据

select session, avg(end-start) from (
    select * 
    from view
         left join (select max(id) as max_id, min(id) as min_id, session
                    from view
                    group by sesion) exclude ON view.session=exclude.session 
                         AND (view.id=exclude.min_id or view.id=exclude.max_id)
    having exclude.session is null) pure_data
group by session

平均数据