SQL Sum of last X Sum of records

前端 未结 2 1884
耶瑟儿~
耶瑟儿~ 2021-01-13 14:52

I\'ve looked for a while and I cannot find the answer to this question (maybe I\'m not searching the correct terms or something). Basically, I have a database that has any n

相关标签:
2条回答
  • 2021-01-13 15:23

    Here is an idea using correlated subqueries:

    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
    
    0 讨论(0)
  • 2021-01-13 15:41

    To get your last 100 dates,

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

    You can simplify your first query with something as simple as

    SELECT date, SUM(passing) as numpassing, SUM(Measured) as nummeasured
    FROM yield
    GROUP BY date
    

    If you need the sum from now until 100 days ago

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

    And if you need the sum from the last 100 dates

    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) 
    
    0 讨论(0)
提交回复
热议问题