SQL - 将表中的某些行复制到同一个表并更改其值

时间:2015-07-30 04:21:03

标签: mysql sql sql-server

我在Microsoft SQL Server中有下表名为CustomerInfo

之前

CustomerInfo

Type         CustomerId          CustParameter        Value
Inbound      StateLOCAL          LastName             Johnson
Inbound      StateLOCAL          ExchangeCode         ALI
Inbound      StateLOCAL          IsPriority           False
Inbound      CityLOCAL           LastName             Rogers
Inbound      CityLOCAL           ExchangeCode         RAR
Inbound      CityLOCAL           IsPriority           True
Inbound      TownBOUND           LastName             Brown
Inbound      TownBOUND           ExchangeCode         JSP
Inbound      TownBOUND           IsPriority           True

我需要把它带到下表

CustomerInfo

Type         CustomerId          CustParameter        Value
Inbound      StateLOCAL          LastName             Johnson
Inbound      StateLOCAL          ExchangeCode         ALI
Inbound      StateLOCAL          IsPriority           False
Inbound      CityLOCAL           LastName             Rogers
Inbound      CityLOCAL           ExchangeCode         RAR
Inbound      CityLOCAL           IsPriority           True
Inbound      TownBOUND           LastName             Brown
Inbound      TownBOUND           ExchangeCode         JSP
Inbound      TownBOUND           IsPriority           True
Inbound      CityBORDER          LastName             Rogers
Inbound      CityBORDER          ExchangeCode         RAR
Inbound      CityBORDER          IsPriority           True

表格更大,我需要它来执行以下操作:

  • 如果CustomerId列中包含单词“LOCAL”,并且CustParameter列包含单词“IsPriority”并且“值”列包含单词“True”
  • 然后需要将具有相同CustomerId的3条记录复制回同一表中。但是,CustomerId列中的单词LOCAL需要更改为单词BORDER,例如,CityLOCAL在复制时变为CityBORDER。

2 个答案:

答案 0 :(得分:1)

尝试这些SQL。

step1:在SQL下面执行。结果没问题。

select Type,  REPLACE(ci.CustomerID, 'LOCAL', 'BORDER'), CustParameter, Value from customerInfo where customerId in (
select distinct CustomerId from customer_info where CustomerId like "%LOCAL%" and CustParameter = "IsPriority" and Value= "True"

第二步:在SQL下面执行。将该记录插入表格。

INSERT INTO customerInfo (Type, CustomerId, CustParameter, Value)
    select Type, REPLACE(ci.CustomerID, 'LOCAL', 'BORDER'), CustParameter, Value from customerInfo where customerId in (
    select distinct CustomerId from customer_info where CustomerId like "%LOCAL%" and CustParameter = "IsPriority" and Value= "True"

    )

谢谢。

答案 1 :(得分:0)

UPDATE
  ci
SET
  ci.CustomerID = REPLACE(ci.CustomerID, 'LOCAL', 'BORDER')
FROM
  CustomerInfo ci
WHERE
  ci.CustomerID IN ( SELECT DISTINCT
                      ci2.CustomerID
                     WHERE
                      ci2.CustomerID LIKE '%LOCAL%'
                      AND ci2.CustParameter LIKE '%IsPriority%'
                      AND ci2.Value = 'True' )