[英]How do I select records where multiple values of different columns have not been exceeded
[英]How do I select records where a value has not been exceeded
我希望從數據庫中提取一份工作ID列表,其中每個工作的狀態未超過給定條件。
對於此示例表,我想顯示所有未超過狀態200的Jobid,並僅顯示最新狀態。
作業進度表
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
我正在尋找的結果是
Jobid Status Date Time
9876 100 20131014 110000
5555 200 20131016 080000
數據庫在AS400上
這是窗口/分析功能的良好用法。
您可以使用row_number()
獲取最新狀態。 您可以使用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;
然后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
在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
這是我能想到的最簡單的方法:
SELECT t.* FROM t
INNER JOIN (
SELECT jobid, max(date) date FROM t
GROUP BY jobid
HAVING COUNT(CASE WHEN status > 200 THEN 1 END) = 0
) s
ON t.jobid = s.jobid AND t.date = s.date
在這里擺弄。
一個通用的表表達式將允許您使用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.