2015-06-02 104 views
2

我試圖構建分析頁面,現在我遇到了問題;用戶根據他們的會話訪問頁面,如果該會話過期,那麼他們被提供一個新的會話。僅使用SQL計算最近的行

我試圖確定一個方法來計算用戶,他們的最後一次會議是使用此查詢某個頁面上的號碼:

SELECT DISTINCT (SELECT MAX(session) FROM analytics b WHERE a.session=b.session) as session,(SELECT MAX(DISTINCT location) FROM analytics c WHERE c.session=a.session) as locale FROM analytics a 

這查詢將返回結果如下:

session |   location    
------------------------------------------ 
1  | http://random-page.io/index.html -- Same session, first entry   
1  | http://random-page.io/index.html -- Same session, second entry   
1  | http://random-page.io/index.html -- Same session, last entry <- What We're trying to Count   
2  | http://random-page.io/index.html -- Same session, first entry   
2  | http://random-page.io/index.html -- Same session, last entry <- What We're trying to Count   
3  | http://random-page.io/index.html -- One session, presumably serves as last and first entry.. but last is what matters <- What We're trying to Count 
4  | http://random-page.io/drafts.html -- One Session <- What We're trying to Count 
5  | http://random-page.io/elements.html -- One session <- What We're trying to Count 

我希望能夠做的是能夠統計其會話僅結束的行,並截斷所有重複結果(通過使用GROUP BY和COUNT),以便我的查詢返回以下內容:

count |   location    
------------------------------------------ 
3  | http://random-page.io/index.html -- The count is 3 and not 5 because there are 3 sessions in which the LAST entry for their assigned session is http://...index.html 
1  | http://random-page.io/drafts.html -- You catch my drift 
1  | http://random-page.io/elements.html -- Coolio <3 

這是可能的嗎?

+1

請提供關於表架構的信息 –

+0

您想要使用「group by」和「count(*)」的組合。 – arkascha

+0

@AbdoAdel你是什麼意思關於表模式的信息? – Brad

回答

1

你可以試試這個:

SELECT 
    COUNT(*) AS count, 
    a.lastEntry AS location 
FROM (
     SELECT 
      session, 
      SUBSTRING_INDEX(GROUP_CONCAT(location), ',', -1) AS lastEntry 
     FROM analytics 
     GROUP BY session 
    ) AS a 
GROUP BY a.lastEntry; 

這裏是sqlfiddle

+0

這工作**完美無缺**,謝謝! – Brad

+0

@Brad很高興幫助:) – Beginner

1

看起來你需要爲這個子查詢...:

SELECT count(session) AS count, location FROM ( 
    SELECT session, location from requests GROUP BY session 
) AS I 
GROUP BY location; 

這裏是一個SQL小提琴玩弄: http://sqlfiddle.com/#!9/41f15/20

+0

檢查此:http://sqlfiddle.com/#!9/fd0b1/1 – Beginner

+0

@Beginner我沒有檢查該flddle,但有什麼意義?看起來像我上面發佈的版本的確切副本。相同的查詢,相同的結果。 – arkascha

+0

同樣的查詢,相同的結果(不應該是),但不是相同的輸入。 – Beginner

1

試試這個(以及它的醜陋,但我不能想出另一種方式來做到這一點)

select 
    grouped_analytics.location, count(grouped_analytics.session) 
from 
    (select 
     analytics.session,analytics.location 
    from 
     analytics 
    group by 
     analytics.session, analytics.location 
    ) as grouped_analytics 
group by 
    grouped_analytics.location