我對MS SQL Server有查詢。該查詢會計算每個商品中有多少商品,並在每個商店中排隊購買和銷售。使用union all從四個不同的表中獲取最新日期
SELECT i.no_,
s2.location,
s2.bincode,
s2.inventory,
s2.purchase,
s2.sale,
s2.defbinflag
FROM dbo.[kasia$item] AS i WITH (nolock)
LEFT OUTER JOIN (SELECT s.itemno,
s.location,
bc.bincode,
Sum(s.inventory) AS Inventory,
Sum(s.purchase) AS Purchase,
Sum(s.sale) AS Sale,
bc.defbinflag
FROM (SELECT [item no_] AS ItemNo,
[location code] AS Location,
Sum(quantity) AS Inventory,
0 AS purchase,
0 AS sale,
[bin code] AS BinCode
FROM dbo.[kasia$warehouse entry] WITH
(nolock
)
WHERE (quantity <> 0)
GROUP BY [item no_],
[location code],
[bin code]
UNION ALL
SELECT no_ AS ItemNo,
[location code] AS Location,
0 AS Inventory,
Sum([outstanding qty_ (base)]) AS purchase,
0 AS sale,
[bin code] AS BinCode
FROM dbo.[kasia$purchase line] WITH (
nolock)
WHERE ([document type] = 1)
AND (type = 2)
GROUP BY no_,
[location code],
[bin code]
UNION ALL
SELECT no_ AS ItemNo,
[location code] AS Location,
0 AS Inventory,
0 AS purchase,
Sum([outstanding qty_ (base)]) AS sale,
[bin code] AS BinCode
FROM dbo.[kasia$sales line] WITH (
nolock)
WHERE ([document type] = 1)
AND (type = 2)
GROUP BY no_,
[location code],
[bin code]
UNION ALL
SELECT [item no_] AS ItemNo,
[transfer-from code] AS Location,
0 AS Inventory,
0 AS purchase,
Sum([outstanding qty_ (base)]) AS sale,
[transfer-from bin code] AS BinCode
FROM dbo.[kasia$transfer line] WITH (
nolock)
GROUP BY [item no_],
[transfer-from code],
[transfer-from bin code]) AS s
LEFT OUTER JOIN
(SELECT DISTINCT
[item no_],
[location code],
[bin code] AS BinCode,
[default] AS DefBinFlag
FROM dbo.[kasia$bin content]
WITH (nolock)
GROUP BY [item no_],
[location code],
[bin code],
[default]) AS bc
ON s.itemno = bc.[item no_]
AND bc.[location code] =
s.location
AND bc.bincode = s.bincode
WHERE (bc.bincode IS NOT NULL)
GROUP BY s.itemno,
s.location,
bc.bincode,
bc.defbinflag) AS s2
ON s2.itemno = i.no_
但我需要需要添加最新的進境之日起在四個表的一個
[kasia$warehouse entry]
[kasia$purchase line]
[kasia$sales line]
[kasia$transfer line]
我怎麼能拿在決勝盤一列包含最後一個條目的日期時間變量從四張桌子?我還沒有試過殺豬此查詢與我試圖讓這將使其成爲不可讀的日期優秀作品,但列如下:
[kasia$warehouse entry] [Expected Receipt Date]
[kasia$purchase line] [Shipment Date]
[kasia$sales line] [Shipment Date]
[kasia$transfer line] [Registering Date]
現在我有這樣的例子,結果:
+---------+----------+---------+-----------+----------+------+------------+
| No_ | location | bincode | inventory | purchase | sale | defbinflag |
+---------+----------+---------+-----------+----------+------+------------+
| 0035513 | dp | V14-3 | 3 | 2 | 1 | 1 |
+---------+----------+---------+-----------+----------+------+------------+
我需要添加一個列的日期。
從我可以告訴,你沒有返回*任何*日期從這些表。我不明白這個問題。 –
是的!我將編輯帖子。 – HellOfACode
不是一個解決方案,而是一個建議。我會將查詢分解成幾個CTE,以便更容易地進行審閱。看着它讓我頭暈目眩。這樣做也可以讓你使用像ROW_NUMBER或DENSE_RANK這樣的窗口函數來確定排序。 – pimbrouwers