SQL最后X个记录的总和

时间:2013-04-17 18:09:12

标签: sql sql-server-2008

我已经找了一段时间,我找不到这个问题的答案(也许我没有找到正确的术语或者其他东西)。基本上,我有一个数据库,每个日期有任意数量的条目。我需要获取包含条目的最后X天的总和(忽略没有条目的天数)。我知道如何找到每天的总和。

假设我有一个名为“收益率”的表:

UnitID  Date        TestTime    NumMeasured NumPassing
1       2013-04-05  10:15       25          3
2       2013-03-31  10:12       30          1
3       2013-03-30  10:12       26          2
4       2013-03-29  10:30       11          1
5       2013-03-31  10:20       6           2
6       2013-04-05  10:30       5           0

然后我使用此查询:

SELECT DISTINCT 
    Date, 
    (
        SELECT SUM([NumMeasured]) 
        FROM [dbo].[Yield] T1 
        WHERE T1.Date = T2.Date
    ) AS 'NumMeasured', 
    (
        SELECT SUM([NumPassing]) 
        FROM [dbo].[Yield] T1 
        WHERE T1.Date = T2.Date
    ) AS 'NumPassing' 
FROM [dbo].[Yield] T2 

获得每日通过/测量的总数:

Date        NumMeasured NumPassing
2013-03-29      11          1
2013-03-30      26          2
2013-03-31      36          3
2013-04-05      30          3

然后我需要一个可以在日期调用的查询(比方说我称之为4/05)获取包含条目的最后X(比如说100天)并返回NumMeasured和NumPassing列的总和那么多天。我无法让这部分工作,我一直在遇到我没有足够经验解决的SQL问题。我正在寻找像

这样的东西
SELECT
    (
        SELECT TOP 100 SUM(T3.[NumMeasured]) 
        FROM T3 
        WHERE T3.Date <= '4/05/2013' 
        ORDER BY T3.Date
    ) AS 'NumMeasured', 
    (
        SELECT TOP 100 SUM(T3.[NumPassing]) 
        FROM T3 
        WHERE T3.Date <= '4/05/2013' 
        ORDER BY T3.Date
    ) AS 'NumPassing', 
    (
        SELECT DISTINCT 
            Date, 
            (
                SELECT SUM([NumMeasured]) 
                FROM [PhaseNoiseMonitoring].[dbo].[Yield] T1 
                WHERE T1.Date = T2.Date
            ) AS 'NumMeasured', 
            (
                SELECT SUM([NumPassing]) 
                FROM [PhaseNoiseMonitoring].[dbo].[Yield] T1 
                WHERE T1.Date = T2.Date
            ) AS 'NumPassing' 
        FROM [PhaseNoiseMonitoring].[dbo].[Yield] T2 
    )
AS T3

预期的查询将返回:

NumMeasured NumPassing
103         9

我意识到这是完全错误的,但我无法弄清楚如何让它发挥作用。

2 个答案:

答案 0 :(得分:1)

以下是使用相关子查询的想法:

with bydays as (<your query here>)
select bd.*,
       (select sum(NumMeasured) from (select top 100 * from bydays bd2 where bd2.date <= bd.date order by date desc) t
       ) as Measured100,
       (select sum(NumPassingd) from (select top 100 * from bydays bd2 where bd2.date <= bd.date order by date desc) t
       ) as Measured100
from bydays

答案 1 :(得分:0)

要获得最近100个日期,

SELECT TOP(100) DISTINCT date FROM yield ORDER BY date desc

您可以使用简单的

简化首次查询
SELECT date, SUM(passing) as numpassing, SUM(Measured) as nummeasured
FROM yield
GROUP BY date

如果您需要从现在起100天前的总和

SELECT SUM(passing) as npassing, SUM(measured) as nmeasured
FROM yield
WHERE date >= DATEADD(d,100,CURRENT)

如果您需要过去100个日期的总和

SELECT SUM(passing) as npassing, SUM(measured) as nmeasured
FROM yield
WHERE date IN (SELECT TOP 100 date FROM yield WHERE date <= '04/05/2013' ORDER BY date desc)