gpt4 book ai didi

SQL Sum of last X Sum of records

转载 作者:行者123 更新时间:2023-12-04 14:20:37 29 4
gpt4 key购买 nike

我已经找了一段时间,但找不到这个问题的答案(也许我没有搜索正确的术语或其他东西)。基本上,我有一个数据库,每个日期有任意数量的条目。我需要取包含条目的最后 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/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

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

最佳答案

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

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

关于SQL Sum of last X Sum of records,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16067105/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com