2014-03-19 61 views
1

有兩個表會議查看其中一個會話可能包含許多觀點:選擇不包括連接表的第一行和最後一行

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 

現在我想獲得的平均長度所有會話的(從的總和計算 - 開始爲屬於會話中的每個視圖)其中,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'; 

回答

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 

平均數據

+0

謝謝您的回答,看起來相當有前途的!使用此查詢,我不斷收到錯誤說「重複列名‘會議’」。另外,我想將結果集限制爲具有app ='A'的會話。 – tilo

+0

它measn有2列有姓名** **會話。只需添加{alial} .session。您可以將應用程序=「A」到查詢 – StanislavL

+0

但爲了包括應用程序,我不得不做另一個連接,右(因爲在你的榜樣,不使用會話表)? – tilo

相關問題