如何根据条件更新列

时间:2016-07-27 09:52:03

标签: mysql

我有一个MySQL表,它看起来像这样。

+----------+-----------+----------+--------------+-------------+
| PONO     | ItemCode  | OrderQty | ReflectedQty | OtherStatus |
+----------+-----------+----------+--------------+-------------+
| PO787HZN | HKQSLUWKN | 30.00    | 30.00        | Posted      |
| PO787HZN | SORHFRBPJ | 40.00    | 40.00        | Posted      |
| PO787HZN | OP8XMREC0 | 50.00    | 50.00        | Posted      |
| PO787HZN | CPD5CGDZ3 | 60.00    | 60.00        | Posted      |
+----------+-----------+----------+--------------+-------------+

随着时间的推移,ReflectedQty列将会更新,它可能看起来像这样

    +----------+-----------+----------+--------------+-------------+
    | PONO     | ItemCode  | OrderQty | ReflectedQty | OtherStatus |
    +----------+-----------+----------+--------------+-------------+
    | PO787HZN | HKQSLUWKN | 30.00    | 20.00        | Posted      |
    | PO787HZN | SORHFRBPJ | 40.00    | 1.00         | Posted      |
    | PO787HZN | OP8XMREC0 | 50.00    | 5.00         | Posted      |
    | PO787HZN | CPD5CGDZ3 | 60.00    | 6.00         | Posted      |
    +----------+-----------+----------+--------------+-------------+

我的问题是,如果列OtherStatus = Partially Received,我如何将列Fully Received更新为ReflectedQty0.00

如何使用select命令实现此目的?

我将通过代码(示例)

来解释这一点
sqlcommand = select reflectedqty from table where reflectedqty = 0.00 and PONo = PO787HZN

if all ReflectedQty of PO787HZN = 0.00 then
'Update OtherStaus to = Fully Received
else
'Update OtherStaus to = Partially Received
end if

接受任何其他代码

TYSM

3 个答案:

答案 0 :(得分:0)

查询如下所示:

UPDATE your_table A
SET A.ReflectedQty = A.ReflectedQty - @valueToBeDeducted,
 A.OtherStatus =
                IF (
                        (A.ReflectedQty - @valueToBeDeducted) <= 0,
                        'Fully Receieved',
                        'Partially Receieved'
                )
WHERE...

valueToBeDeducted是输入参数

如果您想一次更新所有内容:

UPDATE your_table A
SET A.OtherStatus =
IF (
    A.ReflectedQty <= 0,
    'Fully Receieved',
    'Partially Receieved'
)
WHERE <your_condtion_here>

答案 1 :(得分:0)

您可以更新更新查询中的字段,请查看下面的字段。

update yourtable set OtherStaus =(if(ReflectedQty='0.00' and PONO='PO787HZN','Fully Received','Partially Received'));

根据你的条件编写了sql语句。

答案 2 :(得分:0)

SQL Server代码:您需要在MySql中执行类似的操作

UPDATE Table T1 
SET 
OtherStatus = CASE 
                 WHEN T2.RFQ = 0 THEN 'Fully Received'
                 ELSE 'Partially Received'
              END
FROM (
    SELECT PONO, SUM(ReflectedQty) RFQ GROUP BY PONO 
     ) T2 
INNER JOIN ON T2.PONO = T1.PONO