我正在尝试选择附有最新订单的产品 - 配送中心(基于订单日期)。对于一个订单,我可以有多个产品,但整个订单将从一个特定的配送中心发货。 如何选择最新订单附带的特定产品分销中心? 我的结构基本上是这样的:
data.orderdetail
表格包含ordernum
,orderdate
,distributioncenter
我试着像这样拉,但它没有给我想要的结果。我正在使用sql server 2008:
SELECT DISTINCT y.OrderNum, y.Product, y.DistributionCenter
, CAST(y.OrderDate AS DATE) AS Orderdate
FROM (SELECT OrderNum, MAX(CAST(Orderdate AS date)) AS orderdate
FROM data.OrderDetail
GROUP BY OrderNum) AS x
INNER JOIN data.OrderDetail AS y
ON y.OrderNum = x.OrderNum
答案 0 :(得分:0)
看起来你在连接条件中还需要一个子句
你有
ON y.OrderNum = x.OrderNum
将返回与子查询中的订单号匹配的所有订单
但是你需要
ON y.OrderNum = x.OrderNum
AND y.OrderDate = x.orderdate
将返回与子查询中的订单号匹配的所有订单以及该订单号的最大日期
SELECT DISTINCT
y.OrderNum,
y.Product,
y.DistributionCenter,
CAST(y.OrderDate AS DATE) AS Orderdate
FROM (
SELECT
OrderNum,
MAX(CAST(Orderdate AS date)) AS orderdate
FROM data.OrderDetail
GROUP BY OrderNum
) AS x
INNER JOIN
data.OrderDetail AS y
ON y.OrderNum = x.OrderNum
AND y.OrderDate = x.orderdate
答案 1 :(得分:0)
我相信你要找的是row_number。这将按OrderNum对结果集进行分区,然后按OrderDate对集进行排名。然后,您可以在另一个where子句中过滤掉额外的行。
select result.*,
CAST(result.OrderDate as date) as Orderdate,
from (
select y.*,
row_number() over (
partition by y.OrderNum order by CAST(y.OrderDate as date) desc
) rank_
from (
select OrderNum,
MAX(CAST(Orderdate as date)) as orderdate
from data.OrderDetail
group by OrderNum
) as x
inner join data.OrderDetail as y on y.OrderNum = x.OrderNum
) result
where result.rank_ = 1;
答案 2 :(得分:0)
select * from
(
SELECT OrderNum, Product, DistributionCenter, OrderDate
, ROW_NUMBER() over (partition by OrderNum order by OrderDate desc) as rownum
FROM OrderDetail
) as xxx
where xxx.rownum = 1
答案 3 :(得分:0)
试试这个。
; WITH CTE1
AS (
SELECT
od.OrderNum
, od.Product
, od.DistributionCenter
, CAST(od.OrderDate AS DATE) AS OrderDate
, RowNumber = ROW_NUMBER() OVER (PARTITION BY od.Product, od.DistributionCenter ORDER BY CAST(od.OrderDate AS DATE) DESC)
FROM data.OrderDetail od
)
SELECT
OrderNum
, Product
, DistributionCenter
, OrderDate
FROM CTE1
WHERE RowNumber = 1