我有一个带有使用计数器的Oracle表。我需要使用最大计数器值获取每个传感器的完整数据行?
对于ALO,我需要第2行中的数据。 对于AMA,我需要第10行的数据。 对于A11,我需要第9658行的数据。 对于MSP,我需要第9659行中的数据。
非常感谢任何帮助!
谢谢,
戴夫
答案 0 :(得分:1)
您可以使用窗口功能。
ENTITY_GET_LABEL_ORDER = [
'<http://rdf.freebase.com/ns/type.object.name>',
'<http://rdf.freebase.com/ns/common.topic.alias>',
'<http://rdf.freebase.com/key/en>',
'<http://rdf.freebase.com/key/wikipedia.en>',
'<http://rdf.freebase.com/key/wikipedia.en_title>',
]
或使用First window-funcrion。
答案 1 :(得分:0)
如果每个FACILITY_ID_N有两行具有相同的USAGE_COUNTER_N值,则ROW_NUMBER不会返回正确的结果。例如:
SQL> WITH test
2 AS (SELECT 9640 ID_n, 'ALO' sensor_id_c, 317 usage_counter_n FROM DUAL
3 UNION
4 SELECT 9641, 'ALO', 18 FROM DUAL
5 UNION
6 SELECT 9642, 'ALO', 0 FROM DUAL
7 UNION
8 SELECT 9659, 'MSP', 25 FROM DUAL --> MAX for MSP ...
9 UNION
10 SELECT 9660, 'MSP', 10 FROM DUAL
11 UNION
12 SELECT 1000, 'MSP', 25 FROM DUAL --> ... but this is also MAX for MSP
13 )
14 SELECT *
15 FROM (SELECT a.*,
16 ROW_NUMBER ()
17 OVER (PARTITION BY sensor_id_c
18 ORDER BY usage_counter_n DESC) rn
19 FROM test a)
20 WHERE rn = 1;
ID_N SEN USAGE_COUNTER_N RN
---------- --- --------------- ----------
9640 ALO 317 1
1000 MSP 25 1
SQL>
RANK可能会更好:
SQL> l16
16* ROW_NUMBER ()
SQL> c/row_number/rank
16* rank ()
SQL> /
ID_N SEN USAGE_COUNTER_N RN
---------- --- --------------- ----------
9640 ALO 317 1
1000 MSP 25 1
9659 MSP 25 1
SQL>
或者,使用古老的方式:
14 SELECT *
15 FROM test t
16 WHERE t.usage_counter_n = (SELECT MAX (t1.usage_counter_n)
17 FROM test t1
18 WHERE t1.sensor_id_c = t.sensor_id_c)
19 ORDER BY sensor_id_c;
ID_N SEN USAGE_COUNTER_N
---------- --- ---------------
9640 ALO 317
9659 MSP 25
1000 MSP 25
SQL>
答案 2 :(得分:0)
根据您处理重复项的要求,KEEP子句也可能是一个有用的选项
SQL> with test
2 AS (SELECT 9640 ID_n, 'ALO' sensor_id_c, 317 usage_counter_n FROM DUAL
3 UNION
4 SELECT 9641, 'ALO', 18 FROM DUAL
5 UNION
6 SELECT 9642, 'ALO', 0 FROM DUAL
7 UNION
8 SELECT 9659, 'MSP', 25 FROM DUAL --> MAX for MSP ...
9 UNION
10 SELECT 9660, 'MSP', 10 FROM DUAL
11 UNION
12 SELECT 1000, 'MSP', 25 FROM DUAL --> ... but this is also MAX for MSP
13 )
14 SELECT sensor_id_c,
15 min(id_n) keep ( dense_rank first order by usage_counter_n DESC ) id_n,
16 min(usage_counter_n) keep ( dense_rank first order by usage_counter_n DESC ) usage_counter_n
17 from test
18 group by sensor_id_c;
SEN ID_N USAGE_COUNTER_N
--- ---------- ---------------
ALO 9640 317
MSP 1000 25