代码之家  ›  专栏  ›  技术社区  ›  Buda Gavril

请参阅sql中按时间间隔分组的辅助请求的分布

  •  0
  • Buda Gavril  · 技术社区  · 4 年前

    RequestId,Type, Date,        ParentRequestId
    1         1     2020-10-15    null 
    2         2     2020-10-19    1 
    3         1     2020-10-20    null 
    4         2     2020-11-15    3
    

    对于本例,我对请求类型1和2感兴趣,以使示例更简单。我的任务是查询一个大数据库,并根据与父事务的日期差来查看辅助事务的分布。结果如下:

    Interval,Percentage
    0-7 days,50 %
    8-15 days,0 %
    16-50 days, 50 % 
    

    因此,对于预期结果的第一行,我们有id为2的请求,对于来自预期结果的第三行,我们有id为4的请求,因为日期差适合这个间隔。

    如何做到这一点?

    我使用的是sql server 2014。

    1 回复  |  直到 4 年前
        1
  •  0
  •   CoffeeNeedCoffee    4 年前

    我们希望看到您的尝试,但从外观上看,您似乎需要将此表视为两个表,并进行基本分组,但必须做到这一点 设想 在CASE语句上分组。

    WITH dateDiffs as (
        /* perform our date calculations first, to get that out of the way */
        SELECT 
          DATEDIFF(Day, parent.[Date], child.[Date]) as daysDiff,
          1 as rowsFound
        FROM    (SELECT RequestID, [Date] FROM myTable WHERE Type = 1) parent
        INNER JOIN  (SELECT ParentRequestID, [Date] FROM myTable WHERE Type = 2) child
        ON parent.requestID = child.parentRequestID
    )
    
    /* Now group and aggregate and enjoy your maths! */
    SELECT 
      case when daysDiff between 0 and 7 then '0-7'
           when daysDiff between 8 and 15 then '8-15'
           when daysDiff between 16 and 50 THEN '16-50'
           else '50+' 
       end as myInterval,
       sum(rowsFound) as totalFound,
       (select sum(rowsFound) from dateDiffs) as totalRows,
       1.0 * sum(rowsFound) / (select sum(rowsFound) from dateDiffs) * 100.00 as percentFound
    FROM dateDiffs
    GROUP BY 
       case when daysDiff between 0 and 7 then '0-7'
           when daysDiff between 8 and 15 then '8-15'
           when daysDiff between 16 and 50 THEN '16-50'
           else '50+' 
       end;