【问题标题】:Sum score between an effective time range in SQL Server databaseSQL Server 数据库中有效时间范围之间的总和分数
【发布时间】:2020-06-21 02:29:46
【问题描述】:

我在 SQL Server 数据库中有以下示例数据。

UserID Score StartDate   EndDate
------------------------------------
1      10    2019-06-01  2019-07-15
1      20    2019-06-20  2019-07-01
1      30    2019-06-17  2019-07-25
2      10    2019-05-15  2019-06-10
2      20    2019-06-15  2019-07-01
2      30    2019-06-20  2019-07-15

而我需要达到以下结果。

UserID ScoreTotal StartDate   EndDate
----------------------------------------
1      10         2019-06-01  2019-06-17
1      40         2019-06-17  2019-06-20
1      60         2019-06-20  2019-07-01
1      40         2019-07-01  2019-07-15
1      30         2019-07-15  2019-07-25
2      10         2019-05-15  2019-06-10
2      20         2019-06-15  2019-06-20
2      50         2019-06-20  2019-07-01
2      30         2019-07-01  2019-07-15

startdateenddate的分数是否包含在每个计算中都没有关系。

任何帮助将不胜感激。

【问题讨论】:

  • 如果您也可以为您的输出提供逻辑,那将很有帮助
  • 用您正在使用的数据库标记您的问题。

标签: sql-server sum date-range


【解决方案1】:

如果我理解正确,您希望按分数不变的时段累积分数。这有点棘手,因为它可能需要因数据库而异的日期算法。这个想法是取消旋转值并使用聚合和窗口函数:

with tt as (
      select userid, score, startdate as dte
      from t
      union all
      select userid, -score, enddate as dte
      from t
     ) t
select userid, sum(sum(score)) over (partition by userid order by (dte)) as score,
       dte, lead(dte) over (partition by userid order by dte)
from tt
group by userid, dte

【讨论】:

  • 谢谢戈登。我为第一个窗口函数添加了“PARTITION BY userID”,然后它将返回正确的结果。
  • @SeanXu 。 . .我确定了答案。这应该比自连接答案有很多更好的性能。
【解决方案2】:

假设你的关系是A,下面的查询会执行你需要的操作:

WITH unwrapped AS (
    SELECT UserID, SUM(Score) AS Score, StartDate AS TempDate
    FROM A
    GROUP BY UserID, StartDate
    UNION ALL
    SELECT UserID, SUM(-1*Score) AS Score, EndDate AS TempDate
    FROM A
    GROUP BY UserID, EndDate
)
SELECT uw1.UserID, SUM(uw1.Score) AS ScoreTotal, MAX(uw1.TempDate) AS StartDate, uw2.TempDate AS EndDate
FROM unwrapped uw1 INNER JOIN unwrapped uw2
     ON uw1.UserID = uw2.UserID AND uw1.TempDate < uw2.TempDate
GROUP BY uw1.UserID, uw2.TempDate;

【讨论】:

    猜你喜欢
    • 2020-03-10
    • 1970-01-01
    • 1970-01-01
    • 2018-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-21
    • 2021-11-15
    相关资源
    最近更新 更多