当前位置: 代码迷 >> Sql Server >> 怎么用一个表count函数算出来的结果,修改另一个表的字段值
  详细解决方案

怎么用一个表count函数算出来的结果,修改另一个表的字段值

热度:25   发布时间:2016-04-27 11:46:03.0
如何用一个表count函数算出来的结果,修改另一个表的字段值
一个校对表
Proofread

主键 对错状态 错误是属于哪个工程的 行 列
ProPK status PrjGUID x y
1 1 AAA 1 1
2 1 AAA 1 2
3 0 AAA 2 1

status=1表示该行列是错误的

另一个表,记录的是每个工程,校对过没,有多少个错误

ProStatus

主键 多少个错误
PrjGUID errorcount



查询每个工程有多少个错误,用校对表,是

select count(ProPK), Prjguid from proofread where status=1 group by prjguid

每个工程的错误数,应该和状态表的errorcount值相等,但由于某些原因,导致有些工程的这两个值不一样。

现在想用count(ProPK)的值,修改那些和errorcount值不一样的行。


------解决方案--------------------
SQL code
update ProStatusset errorcount = p.errorcountfrom (select count(ProPK), Prjguid from proofread     where status=1 group by prjguid)pwhere t.Prjguid = ProStatus.PrjGUID
------解决方案--------------------
上面一个p写成了t
SQL code
 update ProStatusset errorcount = p.errorcountfrom (select count(ProPK), Prjguid from proofread     where status=1 group by prjguid)pwhere p.Prjguid = ProStatus.PrjGUID
------解决方案--------------------
update PrjGUID 
set errorcount=b.errorcount
from PrjGUID a,(select count(ProPK) errorcount, Prjguid from proofread where status=1 group by prjguid
) b
where a.PrjGUID =b.PrjGUID
------解决方案--------------------
update ProStatus
set errorcount = p.errorcount
from (select count(ProPK) errorcount, Prjguid from proofread 
where status=1 group by prjguid)p
where p.Prjguid = ProStatus.PrjGUID
------解决方案--------------------
SQL code
update aset a.errorcount=isnull(b.errorcount,0)from ProStatus aleft join(select Prjguid,count(ProPK) errorcount from proofread where status=1  group by prjguid) b on a.PrjGUID=b.Prjguid
------解决方案--------------------
终于发现问题的根源了,是
p.Prjguid = a.PrjGUID,这句

因为
select Prjguid,count(ProPK) errorcount
 from proofread where status=1 
 group by prjguid

里的status=1 ,导致,如果在proofread 表里没有记录,就不会有结果,并不是count(ProPK)为null,而是根本就不会有该工程的错误数查出来。

而外面又用了a.PrjGUID =b.PrjGUID,错误数不等的,根本一条也查不出来,查出来的都是相等的。
  相关解决方案