试试这个Query
:
SELECT
DISTINCT
CONVERT(DATETIME,CONVERT(DATE,I.[Date]),101) AS [Date],
I.Nameofitem AS ItemName,
I.Rate AS RATE,
I.Qty AS InQty,
ISNULL(O.Qty,0) AS OutQty,
ISNULL(I.Qty,0)-ISNULL(O.Qty,0) AS Balance,
O.unit AS ItemUnit
FROM Outwards_Master O
RIGHT JOIN Inwards_Master I ON O.Nameofitem=I.Nameofitem
AND CONVERT(DATE,O.[Date])=CONVERT(DATE,I.[Date])
SQL小提琴
注意:由于数据延迟,这不会产生确切的输出。
编辑:
假设(我认为你的结构中有)
1. Inward Master和Outward Master中的所有日期都相同,反之亦然,日期是PRIMARY KEY
2.每个项目都有每个日期的进出数量栏
有了上面的假设,这里是SQL Query
1.TEMP表
SELECT
DENSE_RANK() over(order by I.Date) AS [RANK],
ROW_NUMBER()over(partition by I.Date order by I.Date) AS [VersionId],
I.Date,
I.Nameofitem,
I.Rate,
ISNULL(I.Qty,0) AS INQTY,
ISNULL(O.Qty,0) AS OUTQTY,
I.unit
INTO #TEMP1
FROM
#Inwards_Master I
INNER JOIN #Outwards_Master O ON CONVERT(DATE,O.[Date])=CONVERT(DATE,I.[Date])
AND I.Nameofitem=O.Nameofitem
SELECT * FROM #TEMP1 ORDER BY Date,Nameofitem
2.余额:
;WITH x AS
(
SELECT
[Rank],
[VersionId],
Nameofitem,
[Date],
INQTY,
OUTQTY,
bal=(INQTY-OUTQTY)
FROM #temp1
WHERE [Rank] = 1
UNION ALL
SELECT
y.[Rank],
y.[VersionId],
y.Nameofitem,
y.[Date],
y.INQTY,
y.OUTQTY,
x.bal+(y.INQTY-y.OUTQTY)
FROM x INNER JOIN #temp1 AS y
ON y.[Rank] = x.[Rank] + 1
AND y.VersionId=x.VersionId
and y.Nameofitem=x.Nameofitem
)
SELECT
[Date],
Nameofitem,
INQTY,
OUTQTY,
Balance = bal
FROM x
ORDER BY Date,Nameofitem
OPTION (MAXRECURSION 10000);
这是要验证的 SQL Fiddle