SQL Server添加条件有效的所有行

时间:2018-06-29 18:30:07

标签: sql-server

我有一个SQL Server数据库,我需要在其中添加一个工作族的所有成本。

我有一个这样的桌子

表格:工作

+-------+-----------+-----------+---------+
| wonum |   cost1   |   cost2   | wogroup |
+-------+-----------+-----------+---------+
|   1   |   30.12   |  157.14   |    1    |
|   2   |   110.10  |    0.00   |    1    |
|   3   |   12.67   |   45.45   |    1    |
|   4   |   0.00    |    0.00   |    4    |
|   5   |   400.00  |   11.54   |    4    |
+-------+-----------+-----------+---------+ 

我需要为所有具有相同wogroup的行添加cost1和cost2,但仅对where wonum = wogroup上的行添加。

+-------+-----------+-----------+---------+---------+
| wonum |   cost1   |   cost2   | wogroup |  total  |
+-------+-----------+-----------+---------+---------+
|   1   |   30.12   |  157.14   |    1    | 355.48  |
|   2   |   110.10  |    0.00   |    1    |  null   |
|   3   |   12.67   |   45.45   |    1    |  null   |
|   4   |   0.00    |    0.00   |    4    |  411.54 |
|   5   |   400.00  |   11.54   |    4    |  null   |
+-------+-----------+-----------+---------+---------+

在理想情况下,该行的空值将为cost1和cost2的总和,但我不确定是否可能...

编辑:我只能选择一个,用于BiRT报告

1 个答案:

答案 0 :(得分:1)

由于可以通过添加更多的wonum来改变,所以我将其作为VIEW

declare @work table (wonum  int , cost1 decimal (6,3),  cost2   decimal (6,3) , wogroup int)
insert into @work
values
(1,30.12,157.14,1),
(2,110.10,0.00,1),
(3,12.67,45.45,1),
(4,0.00,0.00,4),
(5,400.00,11.54,4)


select
   *,
   total = case when wonum = min(wonum) over (partition by wogroup) then sum(cost1) over (partition by wogroup) + sum(cost2) over (partition by wogroup) end 
from @work

退货

+-------+-----------+-----------+---------+---------+
| wonum |   cost1   |   cost2   | wogroup |  total  |
+-------+-----------+-----------+---------+---------+
|   1   |   30.12   |  157.14   |    1    | 355.48  |
|   2   |   110.10  |    0.00   |    1    |  null   |
|   3   |   12.67   |   45.45   |    1    |  null   |
|   4   |   0.00    |    0.00   |    4    |  411.54 |
|   5   |   400.00  |   11.54   |    4    |  null   |
+-------+-----------+-----------+---------+---------+

您的查询

select
       *,
       total = case when wonum = min(wonum) over (partition by wogroup) 
                    then sum(cost1) over (partition by wogroup) + sum(cost2) over (partition by wogroup) 
                    else null 
               end 
from work
相关问题