Sql查询以确定何时达到阈值

时间:2013-01-09 14:31:39

标签: sql sql-server-2008

我有一个有趣的SQL问题,我很欣赏一些建议。

我有一个包含列的表:

DateAdded
Score
Team

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

团队成绩的每个成员加在一起,达到阈值得分的团队首先获胜。

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

5 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 Fiddle

答案 2 :(得分: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

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

答案 3 :(得分:0)

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

答案 4 :(得分:0)

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

Sql Fiddle

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