我的表中订单的三种状态为 Entered,Aw Appr&Completed 。 Enter 和 Completed 每行一行,而 AW Appr 每周重复一次,直到完成订单。现在这三个状态都只有一次。 AW Appr 应该是最新的。我正在使用此查询,但它只提供最大月份和最大一周数据。它会选取完整数据的最大周数(包括最近输入的数据)。请帮助增强查询以获取所有三个状态,而 AW Appr 仅是最新状态。
源表 http://sqlfiddle.com/#!18/67924/2
SELECT DISTINCT t1.Contract_Number
,t2.D_Monthx
,t2.D_Reporting_Week
,t2.D_Status
FROM Table1 t1
INNER JOIN (
SELECT DISTINCT max(D_Monthx) D_Monthx
,Max(D_Reporting_Week) D_Reporting_Week
,D_Status
,Contract_Number
FROM Table1
GROUP BY Contract_Number
,D_Status
) t2 ON t1.Contract_Number = t2.Contract_Number
AND t1.D_Monthx = t2.D_Monthx
WHERE t1.Contract_Number = '130100964/2'
结果应为-
答案 0 :(得分:4)
使用Row_Number()
Select Contract_Number, D_Monthx, D_Reporting_Week, D_Status from
(Select *,
Row_Number() over
(partition by Contract_Number,D_Status order by D_Monthx desc)
as ranking
from Table1)c
where ranking=1
答案 1 :(得分:4)
我们可以在此处尝试使用ROW_NUMBER
作为简单的解决方案:
SELECT Contract_Number, D_Monthx, D_Reporting_Week, D_Status
FROM
(
SELECT D_Monthx, D_Reporting_Week, D_Status, Contract_Number,
ROW_NUMBER() OVER (PARTITION BY Contract_Number, D_Status
ORDER BY D_Reporting_Week DESC) rn
FROM yourTable
) t
WHERE rn = 1;
行号在这里很好用,因为对于Entered
和Completed
状态将只出现一次,这意味着它们的行号始终为1。同样,我们要选择的最新AW Appr
的行号也将是一个。