我将3个表与一个公用列“ Load-Id”表连接在一起。哦。和医学博士。 MD的EDI文件在传输电子文件时会更改为另一个名称,因此我只需要显示从上次更新的文件名返回的数据。
我尝试了各种分组和顺序,然后阅读,可以使用Join和Max日期创建一个新列,将数据连接到最后更新的文件名,但继续遇到语法错误
SELECT TOP(100)PERCENT
OD. *
OH.[LOAD_ID] AS [OHLOADID],
OH.[CARRIER],
OH.[CLIENT_REF],
MD.[LOAD_ID] AS [MDLOADID],
MD.[MR_FILE] AS [POFILE]
JOIN (SELECT MR_FILE, MAX(MR_DATE) AS [MDTRANDATE]
FROM dbo.mates_det MD
GROUP BY MR_FILE) MRD ON MD.MR_DATE = MRD.MR_DATE
FROM dbo.out_det OD
LEFT OUTER JOIN DBO.out_head OH ON OH.[LOAD_ID] = OD.[LOAD_ID]
LEFT OUTER JOIN DBO.mates_det ON MD.[LOAD_ID] = OD.[LOAD_ID]
GROUP BY OD.PALLET_ID, OD.SEQ_NO
ORDER BY OD.PALLET_ID, OD.SEQ_NO
每个货盘ID和序列返回1行,如果MRfile名称不止一个,则所有数据都将重复。
名称以PO开头,然后是位置编号244,然后是包含电子数据的zip文件的编号。换句话说
PO2440001.000.zip
PO2440002.000.zip
等等。当到达PO2449999.000.zip时,文件编号再次从PO2440001.000.zip开始,这就是为什么我使用MRfile日期。
根据评论,错误消息为
消息156,级别15,状态1,第118行关键字附近的语法错误 '加入'。消息102,级别15,状态1,第120行附近的语法不正确 “ MRD”。
答案 0 :(得分:0)
尝试一下...
SELECT *
FROM (
SELECT
OD. *
, OH.[LOAD_ID] AS [OHLOADID]
, OH.[CARRIER]
, OH.[CLIENT_REF]
, MD.[LOAD_ID] AS [MDLOADID]
, MD.[MR_FILE] AS [POFILE]
, ROW_NUMBER() OVER (PARTITION BY OD.PALLET_ID, OD.SEQ_NO
ORDER BY MD.MR_DATE DESC) AS rn
FROM dbo.out_det OD
LEFT OUTER JOIN dbo.out_head OH ON OH.[LOAD_ID] = OD.[LOAD_ID]
LEFT OUTER JOIN dbo.mates_det MD ON MD.[LOAD_ID] = OD.[LOAD_ID]
) X
WHERE x.rn = 1
ORDER BY X.PALLET_ID, X.SEQ_NO
答案 1 :(得分:0)
问题是此代码:
MD.[MR_FILE] AS [POFILE]
JOIN (SELECT MR_FILE, MAX(MR_DATE) AS [MDTRANDATE]
FROM dbo.mates_det MD
GROUP BY MR_FILE) MRD ON MD.MR_DATE = MRD.MR_DATE
您将MRD.MR_DATE
作为加入条件。但是,当您进行聚合时,您给MR_DATE列指定了列别名AS [MDTRANDATE]
。
因此您必须使用指定的别名:
MD.[MR_FILE] AS [POFILE]
JOIN (SELECT MR_FILE, MAX(MR_DATE) AS [MDTRANDATE]
FROM dbo.mates_det MD
GROUP BY MR_FILE) MRD ON MD.MR_DATE = MRD.[MDTRANDATE]