以下查询正在撤回以下数据。
我只想为每个产品编号返回一个结果,只有最高的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 :(得分: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