如何查找用户首次订阅产品的时间?

时间:2019-04-23 02:23:06

标签: sql

提供一个sql查询(任何引擎)以计算用户首次订阅该产品的时间。

表:订户

Month     Year  User
January   2016  ZandraDilnot
January   2016  AlfonseMeans
January   2017  KandyChiandotto
February  2017  AlfonseMeans
February  2017  SusanRowan
March     2017  AlfonseMeans
March     2017  ZandraDilnot
March     2017  CrystalPoindexter

我尝试使用Where和group by组合来提出逻辑,但是找不到正确的查询!

选择月份,年份,用户 来自订阅者 哪里(需要检查最小年份) 按用户分组

预期产量

Month     Year  User
January   2016  ZandraDilnot
January   2016  AlfonseMeans
January   2017  KandyChiandotto
February  2017  SusanRowan
March     2017  CrystalPoindexter
... ... ...

3 个答案:

答案 0 :(得分:0)

这可能有效:

SELECT User, MIN(Year),MIN(Month) FROM subscribers GROUP BY User

答案 1 :(得分:0)

这是使用CTE的方法...不是...我在月份中添加了一个额外的列作为数字,以使排序更加容易,而不必进行内联转换。

create table #Test (m1 varchar(100) , m2 smallint ,  y int, u varchar(100));
insert into #Test (m1 , m2 , y , u) values ('January  ',1,2016,'ZandraDilnot      '       )
insert into #Test (m1 , m2 , y , u) values ('January  ',1,2016,'AlfonseMeans      '       )
insert into #Test (m1 , m2 , y , u) values ('January  ',1,2017,'KandyChiandotto   '   )
insert into #Test (m1 , m2 , y , u) values ('February ',2,2017,'AlfonseMeans      '       )
insert into #Test (m1 , m2 , y , u) values ('February ',2,2017,'SusanRowan        '   )
insert into #Test (m1 , m2 , y , u) values ('March    ',3,2017,'AlfonseMeans      '       )
insert into #Test (m1 , m2 , y , u) values ('March    ',3,2017,'ZandraDilnot      '       )
insert into #Test (m1 , m2 , y , u) values ('March    ',3,2017,'CrystalPoindexter '   )

;

with cte1 AS 
(
select * 
    ,  RANK() OVER (PARTITION BY u ORDER BY m2 , y ) AS R
From #test
)
select * 
From cte1 where R = 1;

答案 2 :(得分:0)

一个选项是合并前两列并创建一个日期字段。然后执行以下查询:

按用户选择tbl组中的分钟(分钟)用户

应该工作。