1

我有一个有趣的 SQL 问题,不胜感激。

我有一个包含列的表:

DateAdded
Score
Team

用户将输入他们自己的分数,但它们不一定是有序的(如果他们每天不使用系统,有些可能会过时)。

团队中每个成员的分数相加,首先达到阈值分数的团队获胜。

我想要一个查询,它会告诉我哪个团队首先达到阈值以及在什么日期。

4

5 回答 5

2

您需要的是累积总和。而且,SQL Server 2008 不支持它。好消息,SQL Server 2012 可以。

因此,您可以使用相关子查询来执行此操作:

select team, min(dateadded) as FirstPastThreshold
from (select dateadded, score, team,
             (select sum(score) from t t2 where t2.team = t.team and t2.dateadded <= t.dateadded) as cumulativescore
      from t
     ) t
where cumulativescore>= @threshhold
group by team
于 2013-01-09T14:36:54.957 回答
2

我想,这就是你想要达到的。

SELECT TOP 1 T1.Dateadded, T1.Team FROM Table1 T1
 JOIN Table1 T2
  ON T1.Team = T2.Team
    and T1.Dateadded >= T2.Dateadded
GROUP BY T1.Dateadded, T1.Team
HAVING SUM(T2.Score) >= @Threshold
ORDER BY T1.Dateadded 

SQL小提琴

于 2013-01-09T15:14:46.877 回答
1

您可以DENSE_RANK用来确定达到阈值的最佳/第一团队。

WITH CTE AS
(
  SELECT 
    DateAdded, Score, Team,
    DENSE_RANK() OVER (Order By DateAdded ASC, Score DESC) AS Rank
  FROM dbo.TableName
  WHERE
    Score >= Threshold
)
SELECT 
  DateAdded, Score, Team
FROM CTE
WHERE
  Rank = 1

请注意,这可以返回多个团队。

于 2013-01-09T14:36:45.343 回答
0

您可以添加名为 currentThresholdScore 的第四列。每当插入新记录时, currentThresholdScore 列将是该记录的值 Score 加上已插入的任何先前记录。然后检查 currentThresholdScore 是否超过发送邮件等的阈值。

于 2013-01-09T14:37:18.047 回答
0

您可以使用子查询来解决此问题。只需在查询中添加一列,列出当前分数加上过去分数的总和,然后按日期查找超过阈值的第一条记录

Sql 小提琴

Use tempdb
Create Table Scoring (DateAdded DateTime, Score INT, Team INT)
INSERT Scoring SELECT GetDate(), 100, 1
INSERT Scoring SELECT GetDate()+1, 150, 1
INSERT Scoring SELECT GetDate()+1, 50, 2
INSERT Scoring SELECT GetDate()+2, 75, 2
INSERT Scoring SELECT GetDate()-10, 75, 2


DECLARE @Threshhold INT
SET @Threshhold = 125

-- Table which includes a cumulative score
;WITH tbl AS 
(
SELECT 
    Team, 
    DateAdded, 
    Score, 
    -- This column calculates the current score + the sum of past scores
    IsNull((SELECT Sum(t2.Score) CumScore FROM Scoring t2 WHERE t2.Team = t.Team AND t2.DateAdded < t.DateAdded),0) 
    + Score AS  CumScore
FROM Scoring t
)

-- Find first record > threshold
SELECT TOP 1 * FROM tbl
WHERE CumScore >= @Threshhold
ORDER BY DateAdded ASC
于 2013-01-09T14:50:58.070 回答