如何根据先前的查询结果更新另一个表中的列状态

时间:2019-01-03 11:57:28

标签: sql sql-server

我正在使用SQL Server2014。我运行的查询结果分为2列,一个是ID,另一个是票据编号。

现在在另一个表DW-STG上有列IDTicketnumbercancel_YN

我想要做的是将我先前运行的查询返回的那些票证编号的cancel_YN列的状态更新为Y,并返回IDTicketnumber

下面是输出ID和票证号的查询代码。

select 
    STG2_SBR_PNR_HEADER.HID, DW_SBR_FARES_FAFH.Ticketnumber
from 
    STG2_SBR_PNR_HEADER
join
    DW_SBR_FARES_FAFH on STG2_SBR_PNR_HEADER.HID = DW_SBR_FARES_FAFH.HID

except

select 
    STG2_SBR_FARES_FAFH.HID, STG2_SBR_FARES_FAFH.Ticketnumber 
from 
    STG2_SBR_FARES_FAFH

查询返回的数据样本:

ID     Ticketnumber
-------------------
1      123
2      456

DW_STG表中所需的结果:

ID    Ticket    Cancel_YN
---------------------------------------------------
1     123         Y (previously by default it is N)
2     456         Y (previously by default it is N)
3     745         N

4 个答案:

答案 0 :(得分:0)

如果您发布的查询提供了所需的结果,则可以在更新语句中使用它
,唯一的区别是它必须仅返回列DW_SBR_FARES_FAFH.Ticketnumber

update DW-STG
set cancel_YN = 'y'
where Ticketnumber IN (
  select DW_SBR_FARES_FAFH.Ticketnumber
  from STG2_SBR_PNR_HEADER
  JOIN DW_SBR_FARES_FAFH ON STG2_SBR_PNR_HEADER.HID=DW_SBR_FARES_FAFH.HID
  except
  select STG2_SBR_FARES_FAFH.HID,STG2_SBR_FARES_FAFH.Ticketnumber from 
  STG2_SBR_FARES_FAFH
)

答案 1 :(得分:0)

我会推荐MERGE。请参阅以下示例:

DECLARE @DWSTG TABLE (
    ID int,
    Ticketnumber int,
    cancel_YN char(1)
);

INSERT @DWSTG VALUES
(1,10,'N'),
(2,20,'N'),
(3,30,'N'),
(4,40,'N');

MERGE @DWSTG Dest
USING (
    --here comes your query
    SELECT * FROM (VALUES (2, 20), (3,30)) T(ID, TicketNumber)
) Src
ON Dest.ID=Src.ID AND Dest.TicketNumber = Src.TicketNumber
WHEN MATCHED THEN UPDATE SET cancel_YN = 'Y';

SELECT * FROM @DWSTG;

结果:

ID          Ticketnumber cancel_YN
----------- ------------ ---------
1           10           N
2           20           Y
3           30           Y
4           40           N

答案 2 :(得分:0)

您可以将该查询放入CTE中。
然后在更新中,将表格与其中的唯一票证号相连。

WITH CTE AS
(
   SELECT fafh.Ticketnumber, fafh.HID
   FROM DW_SBR_FARES_FAFH fafh
   JOIN STG2_SBR_PNR_HEADER head ON head.HID = fafh.HID

   EXCEPT

   SELECT Ticketnumber, HID
   FROM STG2_SBR_FARES_FAFH
)
UPDATE t
SET cancel_YN = 'Y'
FROM DW-STG t
JOIN (SELECT DISTINCT Ticketnumber FROM CTE) q
  ON q.Ticketnumber = t.Ticketnumber;

答案 3 :(得分:0)

您可以通过以下方式使用inner join进行尝试。

create table firstResult (ID int, Ticketnumber int)
insert into firstResult values (1, 123), (2, 456)

create table secondResult (ID int, Ticketnumber int, Cancel_YN char(1) default 'N')
insert into secondResult (Id, TicketNumber) values(1, 123),(2, 456),(3,745)

update s 
set s.Cancel_YN = 'Y'
from firstResult as f
inner join secondResult s on s.Ticketnumber = f.TicketNumber

select * from secondResult

在这里,我假设firstResult是第一个查询输出的表,而secondResult表是第二个查询输出的表。 您可以在括号()中用实际查询替换两个表名。