我正在尝试仅获取orderID
的最小日期的记录我有以下设置:
select
op.OrderID,
op.id,
MIN(op.Date) AS Date
From OrderPermits op
GROUP BY
Op.OrderId
op.id,
MIN(op.Date) AS Date
订单有1到多个订单许可。
这里的问题是,当我只想要1个订单ID(订单许可的最小值(日期))时,我仍然会收到重复的订单ID
由于
答案 0 :(得分:4)
WITH q AS
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY OrderID ORDER BY Date) AS rn
FROM orderpermits
)
SELECT *
FROM q
WHERE rn = 1
即使在OrderID
上有关系,也可以保证每MIN(Date)
返回一条记录。
您可能想阅读这篇文章:
答案 1 :(得分:2)
我认为你正在寻找这个:
select op.Date, op.OrderID, op.opid
from (
select OrderID, MIN(Date) AS MinDate
From OrderPermits
GROUP BY OrderId
) opm
inner join OrderPermits op on opm.OrderID = op.OrderID
and opm.MinDate = op.Date
答案 2 :(得分:1)
您需要指定WHERE子句:
SELECT
op.OrderID, op.id, op.Date
FROM
dbo.OrderPermits op
WHERE
op.Date = (SELECT MIN(op.Date) FROM dbo.OrderPermits WHERE OrderId = op.OrderId)
答案 3 :(得分:0)
假设(多次返回除外)您的查询执行了您想要的操作...
select
op.OrderID,
op.id,
MIN(op.Date) AS Date
From OrderPermits op
Where op.Date = (Select Min(Date) from OrderPermits) // <-- Add this
GROUP BY
op.OrderID,
op.id,
MIN(op.Date) as Date
但是,如果你只想要返回一条记录,你也可以这样做:
Select op.OrderID,
op.Id,
op.Date
From OrderPermits op
Where op.Date = (Select MIN(Date) from OrderPermits)
如果多个记录共享MIN(Date)
,这些仍会返回多个结果。我不知道你的数据是否可行。
答案 4 :(得分:-1)
现在无法尝试,但是你不应该从group by子句中删除MIN(of.Date)吗?