4

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

假设我有一个名为“Yield”的表:

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 月 5 日调用它)获取包含条目的最后 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

我意识到这是完全错误的,但我真的不知道如何使它工作。

4

2 回答 2

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
于 2013-04-17T18:22:46.910 回答
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) 
于 2013-04-17T18:22:28.473 回答