0

我将如何修改以下查询以仅返回每个唯一 Part_Number 的最新 Quote_Date 的 Quote.Quote?由于 Quote 是唯一的,我无法只返回第一条记录。我知道这已经以几乎相同的方式被问过很多次了,但是,我不能完全正确地使用 row_number、rank、partition、派生表等......我被卡住了。谢谢你的帮助。

    Sample
    Quote     Part_Number     Quote_Date
    1              a              1/1/12
    2              a              1/2/12
    3              a              1/3/12
    4              b              1/2/12
    5              b              1/3/12
    6              c              1/1/12

    Desired Results
    Quote     Part_Number     Quote_Date
    3              a              1/3/12
    5              b              1/3/12
    6              c              1/1/12

    SELECT Quote.Quote, Quote.Part_Number, MAX(RFQ.Quote_Date) AS Most_Recent_Date
    FROM Quote INNER JOIN RFQ ON Quote.RFQ = RFQ.RFQ
    GROUP BY Quote.Part_Number, Quote.Quote
    HAVING (NOT (Quote.Part_Number IS NULL))
4

3 回答 3

3

partition...order by quote_date desc由于子句,此查询将最大日期编号为“1” 。

select Quote, Part_number, Quote_date,
       rank() over (partition by part_number 
                    order by quote_date desc) as date_order
from sample

在这种情况下,rank() 函数通常比 row_number() 更好。如果您碰巧有两行具有相同的零件号最大日期,则 rank() 会将它们编号相同。要查看它是如何工作的insert into your_table values (7, 'a', '2012-01-03'),然后使用 rank() 运行查询。将其更改为 row_number()。看到不同?

使用WHERE 子句从中选择。

select Quote, Part_number, Quote_date
from 
    (select Quote, Part_number, Quote_date,
            rank() over (partition by part_number 
                         order by quote_date desc) as date_order
    from sample) t1
where date_order = 1;

另一种方法是首先导出一组零件编号和与之相关的最大日期。

select Part_Number, max(Quote_Date) as max_quote_date
from sample
group by Part_number;

然后将其加入原始表以获取您需要的任何其他列。

select s.Quote, s.Part_Number, s.Quote_Date
from sample s
inner join (select Part_Number, max(Quote_Date) max_quote_date
            from sample
            group by Part_number) t1
        on s.Part_Number = t1.Part_number
       and s.Quote_Date = t1.max_quote_date
order by Part_Number;
于 2013-07-02T17:19:24.703 回答
0

CTE 使操作变得如此简单且易于阅读。

;with cte as (
    select
        *,
        row_number() over (partition by Part_Number order by Quote_Date desc) rownum
    from
        @quote
)
select Quote, Part_Number, Quote_Date from cte where rownum = 1
于 2013-07-02T17:26:06.123 回答
0

试一试。我不确定您是否需要 Part_Number where 子句,但您将它包含在原始 SQL 中(作为 HAVING 子句),所以我保留了它。我显然不确切知道您的数据看起来如何,但重要的是子选择的其余部分。

SELECT a.Quote, a.Part_Number, a.Quote_Date
FROM
    (SELECT ROW_NUMBER() OVER(PARTITION BY q.Part_Number ORDER BY r.Quote_Date DESC) AS RowNum,
    q.Quote, q.Part_Number, r.Quote_Date
    FROM Quote q INNER JOIN RFQ r ON q.RFQ = r.RFQ
    WHERE q.Part_Number IS NOT NULL) a
WHERE a.RowNum = 1;
于 2013-07-02T17:12:02.497 回答