2017-10-18 102 views
0

以下查詢將回退以下數據。選擇每個產品類別的最佳結果

enter image description here

我想只返回一個單一的結果每個產品編號,只有最orddate,而且相關的訂單總額(ordttl)和單位成本(ucost)。

想法實施?感謝您的回覆。

SELECT 
ordln.pnum as 'Product Number', 
prod.name as 'Product Name', 
ordhd.snum, 
sup.name, 
ordhd.ordttl, 
ORDHD.onum, 
ORDHD.orddate, 
ordln.ucost 
FROM 
scmdb.dbo.cksprodm prod (NOLOCK) 
INNER JOIN scmdb.dbo.cksordln ordln (NOLOCK) on prod.pnum = ordln.pnum 
INNER JOIN scmdb.dbo.cksordhd ordhd (NOLOCK) on ordhd.onum = ordln.onum 
LEFT JOIN scmdb.dbo.ckssuplr sup (NOLOCK) on ordhd.snum = coalesce(sup.snum, 
sup.asnum) 
WHERE ordhd.orddate BETWEEN 
DATEADD(month,-6,dateadd(day,datediff(day,0,getdate()),0) + '06:00') AND 
GETDATE() -- order date is between 6 months ago and today. 
AND ordln.pnum NOT IN (SELECT distinct PNUM 
        FROM scmdb.dbo.cksquohd qhd 
        inner join scmdb.dbo.cksquoln qln on qhd.quote = qln.quote 
        where qhd.qedate > GETDATE() 
       ) 
+0

無論是使用過一起ROW_NUMBER或交叉應用在上面1 – maSTAShuFu

+0

還能有關係?如果是這樣,他們應該如何處理? – HABO

+0

@HABO由於orddate也包含時間,所以不太可能發生。如果他們真的發生了,任意選擇其中一個結果就沒問題。 –

回答

3

您可以使用ROW_NUMBER按日期進行排序,並獲得最新的日期的一行:

SELECT * 
FROM 
(
    SELECT 
    ordln.pnum as 'Product Number', 
    prod.name as 'Product Name', 
    ordhd.snum, 
    sup.name, 
    ordhd.ordttl, 
    ORDHD.onum, 
    ORDHD.orddate, 
    ordln.ucost, 
    row_number() over (partition by ordln.pnum order by ORDHD.orddate desc) as ranking 
    FROM 
    scmdb.dbo.cksprodm prod (NOLOCK) 
    INNER JOIN scmdb.dbo.cksordln ordln (NOLOCK) on prod.pnum = ordln.pnum 
    INNER JOIN scmdb.dbo.cksordhd ordhd (NOLOCK) on ordhd.onum = ordln.onum 
    LEFT JOIN scmdb.dbo.ckssuplr sup (NOLOCK) on ordhd.snum = coalesce(sup.snum, 
    sup.asnum) 
    WHERE ordhd.orddate BETWEEN 
    DATEADD(month,-6,dateadd(day,datediff(day,0,getdate()),0) + '06:00') AND 
    GETDATE() -- order date is between 6 months ago and today. 
    AND ordln.pnum NOT IN (SELECT distinct PNUM 
         FROM scmdb.dbo.cksquohd qhd 
         inner join scmdb.dbo.cksquoln qln on qhd.quote = qln.quote 
         where qhd.qedate > GETDATE() 
        ) 
) t 
where ranking = 1 
+0

非常簡單的解決方案。謝謝。 –

相關問題