[英]SQL Server 2008 Running Total
I'm aware this has been asked but I'm completely baffled. 我知道有人问过我,但我完全感到困惑。
Trying to run a running total by day using SQL Server 2008. Have looked at solutions elsewhere but would am still completely perplexed. 试图使用SQL Server 2008每天运行总计。曾经在其他地方查看过解决方案,但仍然会感到困惑。
The below code shows Daily sales but I cannot make a running total fit. 下面的代码显示了每日销售额,但我无法得出理想的结果。 Have looked at the similar solutions here but no luck. 在这里看过类似的解决方案,但没有运气。 Have looked at partition by, order by, CTE etc but I'm just not there yet with SQL. 看过分区,排序,CTE等,但是我还不了解SQL。
Would appreciate help, my code is below. 希望得到帮助,我的代码如下。 I know this only returns the total grouped by day... 我知道这只会返回按天分组的总数...
SELECT
dim_invoice_date.invoice_date AS 'Invoice Date',
round(SUM(invoice_amount_corp),2) AS 'Sales'
FROM
fact_om_bud_invoice
JOIN
dim_invoice_date ON fact_om_bud_invoice.dim_invoice_date_key = dim_invoice_date.dim_invoice_date_key
WHERE
dim_invoice_date.current_cal_month IN ('Current')
AND fact_om_bud_invoice.budget_code IN ('BUDGET')
GROUP BY
dim_invoice_date.invoice_date
HAVING
ROUND(SUM(invoice_amount_corp), 2) <> 0
ORDER BY
'Invoice Date'
This returns the output: 这将返回输出:
Invoice Date Sales
-----------------------
4/10/2016 24,132
5/10/2016 15,849
6/10/2016 24,481
7/10/2016 10,243
10/10/2016 42,398
11/10/2016 24,187
Required format is something like: 所需格式如下:
Invoice Date Sales Running Sales
-------------------------------------------
04/10/2016 24,132 24,132
05/10/2016 15,849 39,981
06/10/2016 24,481 64,462
07/10/2016 10,243 74,705
10/10/2016 42,398 117,103
11/10/2016 24,187 141,290
dim_invoice_date is a numeric field, it's looking up a separate date table to display as date time. dim_invoice_date是一个数字字段,它在查找单独的日期表以显示为日期时间。
For example, can use WITH common_table_expression 例如,可以使用WITH common_table_expression
WITH cte AS
(
SELECT
ROW_NUMBER() OVER(ORDER BY h.[Date]) RowN,
h.[Date],
SUM(s.Quantity) q
FROM
Sales s
JOIN Headers h
ON s.ID_Headers = h.ID
WHERE
h.[Date] > '2016.10.31'
GROUP BY
h.[Date]
)
SELECT
c.[Date],
c.q,
SUM(c1.q)
FROM
cte c
JOIN cte c1
ON c1.RowN <= c.RowN
GROUP BY
C.[Date],
c.q
ORDER BY
c.[Date]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.