0

I have a table called users where the employee data are stored. Also I have another table payment_details where employee's payment related data are stored the two tables are as follows.

this table is users

sr_no  emp_no  username  payment

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

This table below is 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

My question here is to update "users" table payment column to "paid" when the status of his/her is all paid in payment_details table

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'2 番目のクエリでは、ユーザーが有料のすべてのステータス ( )を持っているかどうか ( )に関係なく、すべてのユーザーを更新しますnull。最初のクエリでは、支払いを受けた人だけを更新します。

2 番目のクエリの利点は、たとえば、特定のユーザーのすべての'paid' statusオンの 1 つを「未払い」に変更すると、ユーザーのステータスをpayment_detail元に戻すことができることです。paymentnull

于 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 に答える