无法对SQL语句进行分组并计算返回率

无法对SQL语句进行分组并计算返回率,sql,sql-server,Sql,Sql Server,这是我当前的表格: first_date any_date id 2018-12-01 2018-12-01 1234 2018-12-01 2018-12-01 1234 2018-12-01 2018-12-02 1234 2018-12-01 2018-12-01 2434 2018-12-02 2018-12-02 1111 到目前为止,我对MS SQL Server 2017的查询如下所示: select min(any_date) over (PARTI

这是我当前的表格:

first_date  any_date    id
2018-12-01  2018-12-01  1234
2018-12-01  2018-12-01  1234
2018-12-01  2018-12-02  1234
2018-12-01  2018-12-01  2434
2018-12-02  2018-12-02  1111
到目前为止,我对MS SQL Server 2017的查询如下所示:

select
min(any_date) over (PARTITION by id) AS first_time,
any_date,
id
from sales
但是,我希望聚合并添加一个返回率计算,它引用每个唯一的首个\u日期和每个任意\u日期组合。我怎么得到这个

first_date  any_date    count id return_rate
2018-12-01  2018-12-01  2        100% (because this is the cohort start)
2018-12-01  2018-12-02  1        50%
2018-12-02  2018-12-02  1        100%

您可以通过
first\u date
any\u date
进行聚合,然后使用窗口函数
first\u value()
提取队列第一天的不同id计数:

select 
    t.*, 
    1 .0 * count_id 
        / first_value(count_id) over(partition by first_date order by any_date) return_rate
from (
    select first_date, any_date, count(distinct id) count_id
    from sales
    group by first_date, any_date
) t

first_date | any_date | count_id | return_rate :------------------ | :------------------ | -------: | :------------- 01/12/2018 00:00:00 | 01/12/2018 00:00:00 | 2 | 1.000000000000 01/12/2018 00:00:00 | 02/12/2018 00:00:00 | 1 | 0.500000000000 02/12/2018 00:00:00 | 02/12/2018 00:00:00 | 1 | 1.000000000000 首次日期|任何日期|计数| id |返回率| :------------------ | :------------------ | -------: | :------------- 01/12/2018 00:00:00 | 01/12/2018 00:00:00 | 2 | 1.000000000000 01/12/2018 00:00:00 | 02/12/2018 00:00:00 | 1 | 0.500000000000 02/12/2018 00:00:00 | 02/12/2018 00:00:00 | 1 | 1.000000000000 我想你想要:

select first_date, any_date, count(*) as on_this_date,
       count(*) * 1.0 / max(count(*)) over (partition by first_date) as ratio
from (select distinct first_date, any_date, id
      from t
     ) t
group by first_date, any_date;

这假设最大值是第一个值。

什么是计数id?
退货率是如何计算的?看起来count是每个“组”中的项目数,其中组是第一个日期、任何日期和id的不同组合。我不知道为什么id在其预期结果中没有值。他对回报率的评论对我来说意味着,当任何日期=第一天时,回报率应为100%,否则为50%,但这只是一个猜测。@Samcd回报率的计算方式为:#第n天的唯一id/#到达唯一第一天队列开始的唯一id第一天。谢谢。我试图理解你所定义的“第一价值”。您能帮忙吗?@cocoo84hh:
first\u value(count\u id)over(partition by first\u date order by any\u date)
是具有相同
first\u date的最早
任何日期的不同id的计数。换句话说,这是队列开始当天不同ID的计数。我根据您的回复调整了我的查询,这非常有用。但是现在有一些尺寸误差。你能看到这个吗@cocoo84hh:我不知道你在小提琴上想做什么。我只能回答你提出的问题,我想我已经回答了(如果是的话,我建议你接受这个答案)。如果您有更多疑问,我建议您提出一个新问题,包括相关样本数据、预期结果和逻辑解释。