我正在处理SQL查询而且我被困住了。
查询结果应包含以下列:
我试图在主查询中使用子查询,但结果我在LatestIssueDate
和LatestReceiptdate
喜欢这个......
Select Distinct
I.ItemCode,
LatestReceiptDate = (Select top 1 (MH.MoveDate)
from inItem as I
left join InMoveLn as ML on I.ItemID = ML.ItemID
inner join InMoveHd as MH on ML.InvMoveID = MH.InvMoveID
where Mh.transactiontypeID like '5001'
Order by Itemcode desc),
LatestIssueDate = (Select top 1 (MH.MoveDate)
From inItem as I
left join InMoveLn as ML on I.ItemID = ML.ItemID
inner join InMoveHd as MH on ML.InvMoveID = MH.InvMoveID
where Mh.transactiontypeID like
'5013'
or Mh.transactiontypeID like '5003'
Order by ItemCode desc)
from
initemstore as S
left join
initem as I on I.ItemId = S.ItemID
left join
inMoveLn as ML on ML.ItemID = S.ItemID
inner join
inMoveHd as MH on ML.InvMoveID=MH.InvMoveID
order by
I.Itemcode
我花了几个小时,不能再继续了。我将不胜感激任何帮助
这是我使用上面的查询
得到的ItemCode LatestReceiptDate LatestIssueDate
100001 2011-09-12 15:26:18.000 2015-04-14 09:49:07.627
100002 2011-09-12 15:26:18.000 2015-04-14 09:49:07.627
100003 2011-09-12 15:26:18.000 2015-04-14 09:49:07.627
100004 2011-09-12 15:26:18.000 2015-04-14 09:49:07.627
100005 2011-09-12 15:26:18.000 2015-04-14 09:49:07.627
答案 0 :(得分:0)
您的查询很复杂,并且包含与其他表的连接,结果集中没有字段。假设它是正确的你可以写为:
WITH lrd ( ItemCode, LatestReceiptDate )
AS (
SELECT ItemCode, MAX(MH.MoveDate)
FROM inItem AS I
LEFT JOIN InMoveLn AS ML ON I.ItemID = ML.ItemID
INNER JOIN InMoveHd AS MH ON ML.InvMoveID = MH.InvMoveID
WHERE MH.transactiontypeID LIKE '5001'
GROUP BY ItemCode
),
lid ( ItemCode, LatestIssueDate )
AS (
SELECT ItemCode, MAX(MH.MoveDate)
FROM inItem AS I
LEFT JOIN InMoveLn AS ML ON I.ItemID = ML.ItemID
INNER JOIN InMoveHd AS MH ON ML.InvMoveID = MH.InvMoveID
WHERE MH.transactiontypeID LIKE '5013' OR
MH.transactiontypeID LIKE '5003'
GROUP BY ItemCode
)
SELECT
DISTINCT I.ItemCode, lrd.LatestReceiptDate, lid.LatestIssueDate
FROM initemstore AS S
LEFT JOIN initem AS I ON I.ItemId = S.ItemID
LEFT JOIN inMoveLn AS ML ON ML.ItemID = S.ItemID
INNER JOIN inMoveHd AS MH ON ML.InvMoveID = MH.InvMoveID
INNER JOIN lrd ON I.ItemCode = lrd.ItemCode
INNER JOIN lid ON I.ItemCode = lid.ItemCode
ORDER BY I.Itemcode;