每组中最长的项目

时间:2016-05-04 19:32:32

标签: sql oracle

我试图通过设施(给我6个不同的活动)找到最长的活动(1)和(2)设施和部门(给我11个不同的活动)。

此代码仅在

时给出一个回复
SELECT NOC.FCILTY_ID, NAC.ACTIVITY_ID, NAC.ELAPSED_SECONDS
FROM NAC,  NOC
WHERE NAC.OBS_ID=NOC.OBS_ID
AND NAC.ELAPSED_SECONDS IN (SELECT MAX(NAC.ELAPSED_SECONDS) FROM NAC, NOC
GROUP BY NOC.FCILTY_ID)
ORDER BY NOC.FCILTY_ID;

下面给出了一些数据和检索某些数据的代码的示例。

SELECT NAC.OBS_ID, NOC.FCILTY_ID, NOC.DEPT_NO, NAC.ACTIVITY_ID, NAC.ACTIVE_SECONDS, NAC.CAT
FROM NAC, NOC
WHERE NAC.OBS_ID = NOC.OBS_ID;

OBS_ID   FCILTY_ID   DEPT_NO   ACTIVITY_ID   ACTIVE_SECONDS  CAT
1        A           a         132           73.9999584      Motion
2        A           a         133           92.000016       Operations
3        A           a         134           198.0000288     Operations
4        A           a         135           54.9999936      Error/Defect
5        A           a         136           79.0000128      Error/Defect
6        A           a         137           57.9999744      Operations

2 个答案:

答案 0 :(得分:1)

您需要加入子查询。这是一种方式。

with maxInterval as 
(select cat theCat, max(active_seconds) longestTime
from etc
group by cat
)

select whatever
from yourTables join maxInterval on cat = theCat
and active_seconds = longestTime

答案 1 :(得分:1)

使用CTE为每个所需的分组添加ROW_NUMBER,为设施添加rnf,为设施和部门添加rnfd

WITH CTE AS
(SELECT NAC.OBS_ID, NOC.FCILTY_ID, NOC.DEPT_NO, NAC.ACTIVITY_ID, NAC.ACTIVE_SECONDS, NAC.CAT,
ROW_NUMBER() OVER(PARTITION BY NOC.FCILTY_ID ORDER BY ACTIVE_SECONDS  DESC) as rnf,
ROW_NUMBER() OVER(PARTITION BY NOC.FCILTY_ID,NOC.DEPT_NO ORDER BY ACTIVE_SECONDS  DESC) as rnfd 
FROM NAC, NOC
WHERE NAC.OBS_ID = NOC.OBS_ID)
SELECT NAC.OBS_ID, NOC.FCILTY_ID, NOC.DEPT_NO, NAC.ACTIVITY_ID, NAC.ACTIVE_SECONDS, NAC.CAT FROM CTE
WHERE rnf=1 OR rnfd =1

EDIT 对于2个单独的查询

..WHERE rnf=1 

..WHERE rnfd =1