我如何显示不同的一周?

时间:2017-06-05 07:57:21

标签: sql sql-server

我正在执行基于" 运行总计"的SQL代码概念。我的代码是计算准确的运行总数,但我需要在每周完成后才显示运行总计而不是按日期。?

Select DISTINCT SD1.[Week], 
    SD1.[Allocation], 
    SD1.[Subsidiaries],
    SD1.[Month],
    SD1.[Date],
    (SD1.[Daily Sale]+IsNull(SUM(SD2.[Daily Sale]),0)) as 'Running Total'
from [dbo].[Solar data] SD1 
    left join [dbo].[Solar data] SD2 on SD1.[Subsidiaries]=SD2.[Subsidiaries]
        and SD2.[Date]<SD1.[Date] And SD1.[Month]=SD2.[Month]
where SD1.[Subsidiaries]='WCL' 
group by SD1.[Allocation],
    SD1.[Month],
    SD1.[Subsidiaries],
    SD1.[Daily Sale],
    SD1.[Week],SD1.[Date]
order by SD1.[Week]


+---------------+------------+------------+-----------+--------+-------+
| Subsidiaries  | Allocation | Daily Sale |   Date    | Month  | Week  |
+---------------+------------+------------+-----------+--------+-------+
| WCL           |       1075 | 44.93      | 2-Jan-17  | Jan-17 | Week1 |
| WCL           |       1075 | 44.51      | 3-Jan-17  | Jan-17 | Week1 |
| WCL           |       1075 | 53.68      | 8-Jan-17  | Jan-17 | Week2 |
| WCL           |       1075 | 41.45      | 9-Jan-17  | Jan-17 | Week2 |
| WCL           |       1075 | 40.97      | 15-Jan-17 | Jan-17 | Week3 |
| WCL           |       1075 | 55.9       | 16-Jan-17 | Jan-17 | Week3 |
| WCL           |       1075 | 43.89      | 22-Jan-17 | Jan-17 | Week4 |
| WCL           |       1075 | 44.36      | 23-Jan-17 | Jan-17 | Week4 |
| WCL           |       1075 | 35.13      | 29-Jan-17 | Jan-17 | Week5 |
+---------------+------------+------------+-----------+--------+-------+

预期结果:

+--------+---------------+
| Week   | Running total |
+--------+---------------+
| Week1  | 89.44         |
| Week2  | 184.57        |
| Week3  | 281.44        |
| Week4  | 369.69        |
| Week5  | 404.82        |
+--------+---------------+                  

1 个答案:

答案 0 :(得分:0)

你可以尝试

Select DISTINCT SD1.[Week], 
    SD1.[Allocation], 
    SD1.[Subsidiaries],
    SD1.[Month],
    SD1.[Date],
    SUM(Daily Sale) as 'Running Total'
from [dbo].[Solar data] SD1 
where SD1.[Subsidiaries]='WCL' 
group by SD1.[Allocation],
    SD1.[Month],
    SD1.[Subsidiaries],
    SD1.[Daily Sale],
    SD1.[Week],SD1.[Date]
order by SD1.[Week]

这将总结一行的销售额