在where子句中使用子查询更新语句

时间:2018-10-23 14:49:40

标签: sql-server

请帮助在where子句中使用子查询构建UPDATE语句。我有两个表,表ABC有Order,OrderType,Key。表XYZ具有键,行代码。我需要更新Table ABC,从某些行代码传递的Order的Order Type列。 基本数据就像-

    Table - ABC
Order  OrderType  Key
1210    Onnet     AB-1210
2110    Onnet     AB-2110   
1234    Offnet    CD-1234
2345    Onnet     CD-2345
3456    Onnet     AB-3456

Table - XYZ
Key      RowCode
AB-1210  VOICE
AB-1210  VOIP
AB-1210  BVOICE
AB-2110  BVTO
AB-2110  VOIP
AB-2110  CBDE
CD-1234  ABCD
CD-1234  VCET
CD-1234  XYCD

Result
Order  OrderType           Key
1210    Onnet_VOICE       AB-1210
2110    Onnet_VOICE       AB-2110   
1234    Offnet            CD-1234
2345    Onnet             CD-2345
3456    Onnet             AB-3456

更新声明-

UPDATE ABC
SET OrderType= 'Onnet_VOICE'
FROM ABC, XYZ
WHERE Order=  (SELECT Order FROM ABC WHERE ABC.Key = XYZ.Key  AND RowCode IN ('VOICE','VOIP') )
AND ABC.OrderType = 'Onnet'

请帮助。

3 个答案:

答案 0 :(得分:1)

您可以使用UPDATE ... FROM JOIN ...语法:

UPDATE a
SET OrderType = 'Onnet_VOICE'
FROM ABC a
JOIN XYZ x
  ON a.[Key] = x.[Key]
WHERE x.RowCode IN ('VOICE','VOIP') 
  AND a.OrderType = 'Onnet';

答案 1 :(得分:1)

像这样尝试:

import io
import pandas as pd
from PySide import QtCore
import res_rc


file = QtCore.QFile(":/dataset.csv")
if file.open(QtCore.QIODevice.ReadOnly):
    f = io.BytesIO(file.readAll().data())
    df = pd.read_csv(f)
    print(df)

答案 2 :(得分:1)

UPDATE ABC
SET OrderType= 'Onnet_VOICE'
WHERE [Order] IN 
(SELECT DISTINCT [Order] FROM ABC A
JOIN XYZ  X ON X.[KEY] = A.[KEY]
WHERE A.[KEY] = X.[KEY] AND X.[RowCode] IN  ('VOICE','VOIP') AND A.[Ordertype] = 'Onnet')