查询不返回不同的记录

时间:2016-10-19 14:19:15

标签: sql-server stored-procedures distinct

嗨,请你看看为什么我的查询没有返回不同的记录。我希望结果具有以下条件OE1='SCHEDCHNG',每个orderid或ordernum只需要最近的记录意味着每个ordernum或orderid只有一个记录,而dropdate也是null。我的查询如下

    select DISTINCT TOP 100 OE.ORDERID,OE.ID,OE.ORDERNUM,OE.OE4  from OrderExports OE
inner join (
    select ORDERNUM, max(OE4) as MaxDate
    from OrderExports
    group by ORDERNUM
) tm
 on OE.ORDERNUM = tm.ORDERNUM and OE.OE4 = tm.MaxDate
 inner join orde_ O on OE.ORDERID = O.ORDERID 
 WHERE OE1='SCHEDCHNG' AND O.DROPDATE is null 

query result with duplicate record

2 个答案:

答案 0 :(得分:2)

这里的细节相当稀疏,但我认为你想要这些内容。

with SortedResults as
(
    select OE.ORDERID
        , OE.ID
        , OE.ORDERNUM
        , OE.OE4  
        , ROW_NUMBER() over(partition by OE.ORDERID, OE.ORDERNUM order by OE.OE4 desc) as RowNum
    from OrderExports OE
    inner join 
    (
        select ORDERNUM
            , max(OE4) as MaxDate
        from OrderExports
        group by ORDERNUM
    ) tm on OE.ORDERNUM = tm.ORDERNUM and OE.OE4 = tm.MaxDate
     inner join orde_ O on OE.ORDERID = O.ORDERID 
     WHERE OE1='SCHEDCHNG' 
        AND O.DROPDATE is null 
)

select ORDERID
    , ID
    , ORDERNUM
    , OE4
from SortedResults
where RowNum = 1

答案 1 :(得分:0)

您可以尝试使用max和group by,如下所示:

SELECT a.ID, max(a.ORDERID) as OrderID, max(a.ORDERNUM) as OrderNum,MAX(OE.OE4) as OE4 FROM
(
--your query
 ) a
 group by a.ID