我有两个sql语句: SQL 1:
SELECT
[PO].[No.],
[PO].[SD],
[PO].[oNo.],
[PO].[StCN],
[POL].[OC] as S_text
FROM [PO]
INNER JOIN
[POL]
ON [POL].[No.] = [PO].[No.]
INNER JOIN (
SELECT [POL].[No.],
MAX([POL].[Line No.])as MaxLine
FROM [POL]
WHERE [POL].[EP]='1'
GROUP BY [POL].[No.]
) as MaxLineTable
ON [POL].[No.] = MaxLineTable.[No.]
AND [POL].[Line No.] = MaxLineTable.MaxLine
WHERE [PO].[Status] <> 3
AND [PO].[Plant] = '0025'
ORDER BY [PO].[SD]
SQL语句的结果:
NO. | SD | oNo | StCN | S_text
P001 | 1/1/16 | O100 | CustA | Step 2
P002 | 2/1/16 | O100 | CustA | Step 59
P006 | 9/1/16 | O103 | CustC | Step 10
P005 | 1/2/16 | O101 | CustB | Step 4
和SQL 2:
SELECT
[PO].[No.],
[PO].[SD],
[PO].[oNo.],
[PO].[StCN],
"Some Tekst" as S_text
FROM [PO]
WHERE [PO].[Status] <> 3
AND [PO].[Plant] = '0025'
ORDER BY [PO].[SD]
SQL语句的结果:
NO. | SD | oNo | StCN | S_text
P001 | 1/1/16 | O100 | CustA | Some Text
P003 | 1/1/16 | O104 | CustC | Some Text
P002 | 2/1/16 | O100 | CustA | Some Text
P006 | 9/1/16 | O103 | CustC | Some Text
P005 | 1/2/16 | O101 | CustB | Some Text
P004 | 6/2/16 | O207 | CustA | Some Text
SQL 1始终是sql2的子集。我想要的是sql 2的结果,所有行中都有S_text的附加信息。
我想要的输出:
NO. | SD | oNo | StCN | S_text
P001 | 1/1/16 | O100 | CustA | Step 2
P003 | 1/1/16 | O104 | CustC | Some Text
P002 | 2/1/16 | O100 | CustA | Step 59
P006 | 9/1/16 | O103 | CustC | Step 10
P005 | 1/2/16 | O101 | CustB | Step 4
P004 | 6/2/16 | O207 | CustA | Some Text
答案 0 :(得分:0)
可以是两个选择
之间的左连接select No, SD, oNo, StCN, ISNULL(t2.S_text, "Some Tekst" )
FROM (
SELECT
[PO].[No.] as No,
[PO].[SD] as SD ,
[PO].[oNo.] as oNo,
[PO].[StCN] as StCN
FROM [PO]
WHERE [PO].[Status] <> 3
AND [PO].[Plant] = '0025'
) t1
left join (
SELECT
[PO].[No.] as No,
[PO].[SD] as SD ,
[PO].[oNo.] as oNo,
[PO].[StCN] as StCN
[POL].[OC] as S_text
FROM [PO]
INNER JOIN
[POL]
ON [POL].[No.] = [PO].[No.]
INNER JOIN (
SELECT [POL].[No.],
MAX([POL].[Line No.])as MaxLine
FROM [POL]
WHERE [POL].[EP]='1'
GROUP BY [POL].[No.]
) as MaxLineTable
ON [POL].[No.] = MaxLineTable.[No.]
AND [POL].[Line No.] = MaxLineTable.MaxLine
WHERE [PO].[Status] <> 3
AND [PO].[Plant] = '0025'
) t2
left join
ORDER BY t1.[SD]