문제

I have a simple table.

 Date | Revenue
 5/1    12
 5/2    25
 5/3    93
 .
 .
 11/15  47

I am trying to write a query that returns two columns. The first column is Date, day-by-day, like the original table. The second column is 30-Day-Revenue, which is the sum of the "Revenue" column in the original table for the last 30 days, ending on the displayed date. There is a lot of overlap when we sum. Thanks in advance!

도움이 되었습니까?

해결책

I have an alternative solution (assumes your table is called revenue_table):

SELECT a.Date, SUM(b.Revenue)
FROM revenue_table a, revenue_table b
WHERE b.Date <= a.Date AND b.Date > a.Date - 30
GROUP BY a.Date;

다른 팁

SELECT table1.Date, table1.Revenue, Past30DayRevenue = SUM(table2.Revenue)
FROM    insert_your_table_name_here table1
        JOIN insert_your_table_name_here table2 ON DATEDIFF(day, table2.Date, table1.Date) BETWEEN 0 AND 29
GROUP BY table1.Date, table1.Revenue
ORDER BY table1.Date;

You can do this by using subqueries. E.g.

SELECT outer.date, (SELECT SUM(inner.revenue) 
                    FROM table inner 
                    WHERE inner.date > outer.date-30) AS thirtydayrevenue
FROM table outer
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top