我正在加入表格,我的代码如下所示:
SELECT P.*
FROM (
SELECT ABC.StockCode
,ABC.Supplier
,ABC.Price
,MAX(ABC.OrigReceiptDate) ReceiptDate
FROM (
SELECT GRND.StockCode
,GRND.Supplier
,OrigReceiptDate
,(GRND.OrigGrnValue / GRND.QtyReceived) AS Price
FROM [SysproCompanyR].[dbo].[GrnDetails] GRND
WHERE QtyReceived > 0
) ABC
GROUP BY ABC.StockCode
,ABC.Supplier
,ABC.Price
) P
WHERE P.StockCode IN (
SELECT StockCode
FROM [SysproCompanyR].[dbo].[InvMaster]
)
ORDER BY P.StockCode
,P.Price
然而,结果集是:
我的问题是我需要获取最新购买的股票代码及其价格......但由于价格不同,任何想法帮助金发女郎>
我得到重复的价值答案 0 :(得分:3)
试试这个:
WITH CTE
AS
(
SELECT
ABC.StockCode,
ABC.Supplier,
ABC.Price,
ABC.OrigReceiptDate AS ReceiptDate,
ROW_NUMBER() OVER(PARTITION BY ABC.Supplier
ORDER BY ABC.OrigReceiptDate DESC) AS RN
FROM
(
SELECT GRND.StockCode, GRND.Supplier,OrigReceiptDate,
(GRND.OrigGrnValue /GRND.QtyReceived) as Price
FROM [SysproCompanyR].[dbo].[GrnDetails] GRND
Where QtyReceived > 0
) AS ABC
INNER JOIN [SysproCompanyR].[dbo].[InvMaster] AS m
ON ABC.StockCode = m.StockCode
)
SELECT
StockCode,
Supplier,
Price,
ReceiptDate
FROM CTE
WHERE RN = 1;
这应该为您提供每个供应商最新购买的股票代码及其价格。
答案 1 :(得分:0)
我相信这种形式的查询更容易理解,并且可以轻松维护:
;WITH ABC AS (
SELECT
GRND.StockCode,
GRND.Supplier,
OrigReceiptDate,
Price = (GRND.OrigGrnValue / GRND.QtyReceived),
FROM [SysproCompanyR].[dbo].[GrnDetails] GRND
WHERE QtyReceived > 0
),
P AS (
SELECT
ABC1.StockCode,
lastOne.Supplier,
lastOne.Price,
ReceiptDate = lastOne.OrigReceiptDate
FROM
(SELECT DISTINCT StockCode FROM ABC) ABC1
CROSS APPLY(
SELECT TOP 1
Supplier,
Price,
OrigReceiptDate
FROM ABC
WHERE StockCode = ABC1.StockCode
ORDER BY OrigReceiptDate DESC
) lastOne
)
SELECT *
FROM P
WHERE
StockCode IN (
SELECT StockCode
FROM [SysproCompanyR].[dbo].[InvMaster])
ORDER BY
StockCode,
Price
答案 2 :(得分:0)
WHERE子句
中的操作符EXISTS和相关子查询的另一个选项SELECT P.*
FROM (
SELECT GRND.StockCode, GRND.Supplier, GRND.OrigReceiptDate, (GRND.OrigGrnValue / GRND.QtyReceived) AS Price
FROM [SysproCompanyR].[dbo].[GrnDetails] AS GRND
WHERE QtyReceived > 0
) P
WHERE P.StockCode IN (
SELECT StockCode
FROM [SysproCompanyR].[dbo].[InvMaster]
)
AND EXISTS(
SELECT 1
FROM [SysproCompanyR].[dbo].[GrnDetails] AS GRND2
WHERE GRND.StockCode = GRND2.StockCode
AND GRND.Supplier = GRND2.Supplier
HAVING MAX(GRND2.OrigReceiptDate) = GRND.OrigReceiptDate
)
ORDER BY P.StockCode, P.Price
答案 3 :(得分:0)
我认为你可以这样做:
SELECT a.*
FROM( SELECT StockCode,
Supplier,
OrigGrnValue/QtyReceived) AS Price,
OrigReceiptDate AS ReceiptDate
ROW_NUMBER() OVER (PARTITION BY StockCode, Supplier, OrigGrnValue/QtyReceived ORDER BY OrigReceiptDate DESC) as rown
FROM GrnDetails
WHERE QtyReceived > 0 ) a
WHERE a.rown = 1
AND a.StockCode EXISTS (SELECT StockCode
FROM [SysproCompanyR].[dbo].[InvMaster] m
WHERE m.StockCode = a.StockCode)
ORDER BY a.StockCode,
a.Price