0

我有一个名为 users 的表,用于存储员工数据。此外,我还有另一个表 payment_details 存储员工的付款相关数据,这两个表如下。

这张表是用户

sr_no  emp_no  username  payment

1     1001      leroy    <null>
2     1003      harry    <null>
3     1004      Tom      <null>   
4     1008      Jon      <null>    

下表是payment_details

    sr_no       name     number      month    status        date
      43        Jon       1008       January  paid         5/16/2012
      44        Jon       1008       January  balance      5/16/2012
      45        Harry     1003       January  paid         5/16/2012
      46        Tom       1004       January  paid         5/16/2012
      47        leroy     1001       January  paid         5/16/2012
      48        Jon       1008       January  paid         5/16/2012
      49        Harry     1003       January  paid         5/16/2012
      50        Jon       1008       February balance      5/16/2012
      51        leroy     1001       February paid         5/16/2012
      52        Jon       1008       February paid         5/16/2012
      53        Tom       1004       February balance      5/16/2012

我的问题是当他/她的状态全部在payment_details表中支付时,将“users”表支付列更新为“paid”

4

3 回答 3

3

您可以这样做:http ://www.sqlfiddle.com/#!3/db13f/18

update users set payment = 'paid'
from
(
  select number
  from payment_details
  group by number
  having sum(case when status = 'paid' then 1 end) 
       = count(*)
) as x
where x.number = users.emp_no;

或者这个:http ://www.sqlfiddle.com/#!3/db13f/19

update users
  set payment = x.upd
from 
(
  select u.emp_no, 

      case when sum(case when d.status = 'paid' then 1 end)  = count(*) then
         'paid'
      else
         null
      end as upd

  from users u

  left join payment_details d
  on d.number = u.emp_no

  group by u.emp_no
) as x
where x.emp_no = users.emp_no;

它们的区别在于它更新了多少行。在第二个查询中,它会更新所有用户,无论用户是否具有已付费状态('paid')或没有(null);在第一个查询中,它只更新那些付费的人。

第二个查询的优点是,例如,当您将给定用户的全部'paid' status内容之一更改payment_detail为“未付费”时,它可以将用户的payment状态恢复为null

于 2012-05-17T09:00:00.673 回答
1
UPDATE order_details
SET payment= 'paid'
WHERE not EXISTS (SELECT 1
              FROM payment_details 
              WHERE payment_details.emp_no= order_details.emp_no
              AND   payment_details.status <> 'paid'
             )
于 2012-05-17T07:07:40.510 回答
0

还有一种简单的方法可以将详细信息表的值转换为变量并更新表,如下所示:

declare @bb varchar(50)
select @bb= status from payment_details where name=@name and id=@id
update uuser set payment = @bb
where name = @name and id=@id
于 2012-05-17T08:10:05.453 回答