WITH A -- Get a list of unique combinations of Shipmentnumber and ShipmentType
AS (
SELECT Distinct
f_Shipmentnumber
, f_ShipmentType
FROM t_shipment
)
, B -- Get a list of all those shipmentnumbers values that have more than one shipmentType associated
AS (
SELECT f_Shipmentnumber
FROM A
GROUP BY
f_Shipmentnumber
HAVING COUNT(*) > 1
)
SELECT
A.f_Shipmentnumber
, A.f_ShipmentType
FROM A
JOIN B
ON A.f_Shipmentnumber = B.f_Shipmentnumber
这就是我所拥有的并且它返回的很漂亮然而我需要设置shipmentType = 1,其中shipmentTyp = 2只是为了这些结果。
答案 0 :(得分:1)
您可以使用另一个CTE进行最后一次选择,然后只使用更新语句:
WITH A -- Get a list of unique combinations of Shipmentnumber and ShipmentType
AS (
SELECT Distinct
f_Shipmentnumber
, f_ShipmentType
FROM t_shipment
)
, B -- Get a list of all those shipmentnumbers values that have more than one shipmentType associated
AS (
SELECT f_Shipmentnumber
FROM A
GROUP BY
f_Shipmentnumber
HAVING COUNT(*) > 1
), C -- This CTE will be the one for your update statement, assuming that f_shipmentnumber is a primary key
AS (
SELECT
A.f_Shipmentnumber
, A.f_ShipmentType
FROM A
JOIN B
ON A.f_Shipmentnumber = B.f_Shipmentnumber
)
UPDATE t_shipment
SET f_ShipmentType = 1
FROM C as cte
JOIN t_shipment s ON cte.f_shipmentnumber = s.f_shipmentnumber
WHERE cte.f_shipmenttype = 2
请注意,update语句只是通过f_shipmentnumber
加入最终的CTE结果,更新只会更新最终select语句中返回的记录,现在包含在CTE中。
答案 1 :(得分:0)
如果您想要1
更改2
,请使用CASE
SELECT
CASE WHEN A.f_Shipmentnumber = 2
THEN 1
ELSE A.f_Shipmentnumber
END as f_Shipmentnumber
, A.f_ShipmentType
FROM A
JOIN B
ON A.f_Shipmentnumber = B.f_Shipmentnumber