使用SQL仅计算最近的行

时间:2015-06-02 19:41:03

标签: php mysql

我正在尝试构建一个分析页面,现在我遇到了一个问题;用户根据会话访问页面,如果该会话过期,则会向他们提供新会话。

我正在尝试使用此查询确定一种方法来计算他们上次会话在某个页面上的用户数量:

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

这一切都可能吗?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

答案 2 :(得分: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