我正在比较2个表。 表1列1-5。 表2列1-6。
如何在table1
中添加包含完整内容的第6列(来自table2)答案 0 :(得分:0)
以下是如何实现这一目标的示例:
DECLARE @FirstTable TABLE (
FirstFirst VARCHAR(5),
FirstSecond VARCHAR(5),
FirstThird VARCHAR(5),
FirstFourth VARCHAR(5),
FirstFifth VARCHAR(5))
INSERT INTO @FirstTable
VALUES
( '111', '121', '131', '141', '151' ),
( '112', '122', '132', '142', '152' ),
( '113', '123', '133', '143', '153' )
DECLARE @SecondTable TABLE (
SecondFirst VARCHAR(5),
SecondSecond VARCHAR(5),
SecondThird VARCHAR(5),
SecondFourth VARCHAR(5),
SecondFifth VARCHAR(5),
SecondSixth VARCHAR(5))
INSERT INTO @SecondTable
VALUES
( '111', '121', '131', '141', '151', '161' ),
( '112', '122', '132', '142', '152', '162' ),
( '113', '123', '133', '143', '153', '163' )
--As a join
SELECT ft.*, st.SecondSixth FROM @FirstTable AS ft
LEFT JOIN @SecondTable AS st ON
ft.FirstFirst = st.SecondFirst AND
ft.FirstSecond = st.SecondSecond AND
ft.FirstThird = st.SecondThird AND
ft.FirstFourth = st.SecondFourth AND
ft.FirstFifth = st.SecondFifth
--As outer apply
SELECT ft.*, oa_secondTable.SecondSixth FROM @FirstTable AS ft
OUTER APPLY (
SELECT TOP 1 st.SecondSixth FROM @SecondTable AS st
WHERE
ft.FirstFirst = st.SecondFirst AND
ft.FirstSecond = st.SecondSecond AND
ft.FirstThird = st.SecondThird AND
ft.FirstFourth = st.SecondFourth AND
ft.FirstFifth = st.SecondFifth
) AS oa_secondTable
简短说明 - 两张桌子 - 第一个例子是与加入的比较 - 第二个例子是与外部申请比较