[英]How do I select records where a value has not been exceeded
I wish to extract from a database a list of job Ids where the status for each job has not exceeded a given criteria. 我希望从数据库中提取一份工作ID列表,其中每个工作的状态未超过给定条件。
For this example table I want to display all the jobid that have not exceeded status 200 and display only the latest status. 对于此示例表,我想显示所有未超过状态200的Jobid,并仅显示最新状态。
Job-Progress table 作业进度表
Jobid Status Date Time
1234 100 20131001 080000
1234 200 20131001 100000
1234 300 20131001 140000
9876 100 20131014 110000
5555 100 20131015 100000
5555 200 20131016 080000
The result i am looking for is 我正在寻找的结果是
Jobid Status Date Time
9876 100 20131014 110000
5555 200 20131016 080000
Database is on AS400 数据库在AS400上
This is a good use of window/analytic functions. 这是窗口/分析功能的良好用法。
You can use row_number()
to get the most recent status. 您可以使用
row_number()
获取最新状态。 You can use sum() over
to count the number of times that status exceeds 200. 您可以使用
sum() over
来计算状态超过200的次数。
select jobid, Status, Date, Time
from (select jp.*,
row_number() over (partition by jobid order by date desc, time desc) as seqnum,
sum(case when status >= 200 then 1 else 0 end) over (partition by jobid) as status_200
from JobProgress jp
) jp
where status_200 = 0 and seqnum = 1;
The where
clause then filters to the rows you are looking for. 然后
where
子句将过滤到要查找的行。
select t1.*
from your_table t1
inner join
(
select Jobid, max(date*1000000+time) as maxdt
from your_table
group by jobid
having sum(case when status > 200 then 1 else 0 end) = 0
) t2 on t1.jobid = t2.jobid
and t1.date*100000+t1.time = maxdt
In SQL server you can use ROW_NUMBER
: 在SQL Server中,您可以使用
ROW_NUMBER
:
SELECT *
FROM (SELECT
Jobid,
status,
ROW_NUMBER() OVER(PARTITION BY Jobid ORDER BY Date DESC) AS rn
FROM
Job-Progress
WHERE Status < 200) A
WHERE RowNum = 1
A common table expression will allow you to employ the ROW_NUMBER() function to mark the latest row of each job as 1. Then all you need to do is pick that row whenever its status is acceptable. 一个通用的表表达式将允许您使用ROW_NUMBER()函数将每个作业的最新行标记为1。然后,您所要做的就是在状态允许的情况下选择该行。
With x as
(SELECT *,
ROW_NUMBER() OVER(PARTITION BY Jobid ORDER BY Date, time DESC) AS pick
FROM JobProgress
)
SELECT jobid, status, date, time
FROM x
WHERE Status <= 200
And pick = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.