Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
T-SQL更新问题_Sql_Sql Server - Fatal编程技术网

T-SQL更新问题

T-SQL更新问题,sql,sql-server,Sql,Sql Server,有两个表A和表B 表A Date Budget 9-1-2016 21 9-2-2016 10 表B Date Amount Budget 9-1-2016 12 9-1-2016 15 9-1-2016 17 9-2-2016 15 9-2-2016 10 9-3-2016 12 我想将表A中的每日预算划分为中的相应项目 表B如下:

有两个
表A
表B

表A

Date          Budget
9-1-2016        21
9-2-2016        10
表B

Date          Amount      Budget
9-1-2016        12
9-1-2016        15
9-1-2016        17
9-2-2016        15
9-2-2016        10
9-3-2016        12
我想将表A中的每日预算划分为中的相应项目 表B如下:

Date          Amount      Budget
9-1-2016        12          7
9-1-2016        15          7
9-1-2016        17          7
9-2-2016        15          5
9-2-2016        10          5
9-3-2016        12          0

例如,表A
中的
9-1-2016
预算被划分为表B
中日期相同的3个项目。

这应该完成以下工作:

注意,我使用了表a的左连接,只是为了处理不存在的预算

update tableB
set Budget = coalesce(a.Budget,0) / c.numB
from tableB b
     left join tableA a on a.Date = b.Date
     inner join (select Date, count(*) as numB
                 from tableB
                 group by date) c on c.Date = b.Date;

基于什么逻辑。。。。。?你的数字没有任何意义。预算应在同一日期从表A分摊到表B。因此,表A中的日期(2016年9月1日)的预算值为21。我希望这个值在表B中等分,因为该日期有三行。现在这有意义吗?我很乐意解释更多。谢谢。这太棒了。你能提供一个更新声明吗。非常感谢你