SQL - 如何找到用户的第一个页面?

SQL - How to find which page is the first for users?

我有一个 table 这样的:

+----------+-------------------------------------+----------------------------------+
| user_id  | time                                | url                              |
+----------+-------------------------------------+----------------------------------+
| 1        | 02.04.2017 8:56                     | www.landingpage.com/              | 
| 1        | 02.04.2017 8:57                     | www.landingpage.com/about-us     |  
| 1        | 02.04.2017 8:58                     | www.landingpage.com/faq          |
| 2        | 02.04.2017 6:34                     | www.landingpage.com/about-us     |
| 2        | 02.04.2017 6:35                     | www.landingpage.com/how-to-order |
| 3        | 03.04.2017 9:11                     | www.landingpage.com/             |
| 3        | 03.04.2017 9:12                     | www.landingpage.com/contact      |
| 3        | 03.04.2017 9:13                     | www.landingpage.com/about-us     |
| 3        | 03.04.2017 9:14                     | www.landingpage.com/our-legacy   |
| 3        | 03.04.2017 9:15                     | www.landingpage.com/             |
+----------+-------------------------------------+----------------------------------+

我想弄清楚哪个页面是大多数用户的第一个页面(用户访问网站时看到的第一个页面)并计算它被视为第一页的次数。

有没有办法编写查询来执行此操作?我想我需要使用

MIN(time)

结合分组,但我不知道如何。

所以关于我提供的样本应该是这样的:

url                                       url_count
---------------------------------------------------
www.landingpage.com/                      2            
www.landingpage.com/about-us              1            

谢谢!

你说得对,你需要在子选择中使用 min() 聚合函数。

select
  my_table.url
from
  my_table
where
  my_table.time = (
    select
      min(t.time)
    from
      my_table t
    where
      t.user_id = my_table.user_id
  )

my_table 替换为 table 的实际名称。


要包括用户浏览过的页面数量,您需要这样的内容:

select
  my_table.url
  , (
    select
      count(t.url)
    from
      my_table t
    where
      t.user_id = my_table.user_id
  ) as url_count
from
  my_table
where
  my_table.time = (
    select
      min(t.time)
    from
      my_table t
    where
      t.user_id = my_table.user_id
  )
SELECT * 
FROM my_table
WHERE time IN 
(
  SELECT min(time) 
  FROM my_table
  GROUP BY url
);

您可以通过以下方式查询:

Select top (1) with ties * 
    from yourtable
order by row_number() over(partition by user_id order by [time])

您可以使用外部查询来获得相同的结果:

Select * from (
    Select *, RowN = row_number() over(partition by user_id order by [time]) from yourtable) a
Where a.RowN = 1