Oracle获取不在groupby分组中的字段
背景介绍:
1. 需要按照车辆类型分类,出省油冠军(百公⾥油耗最低);
雪福来普通分组函数可以出对应的车辆类型及省油冠军,但是⽆法查询到车辆唯⼀标识;
select MIN(TO_NUMBER(M.OIL100MILE)),B.C_USE_TYPE from iov_screen_data_month M
left join ANALYSIS.IOV_CAR_BASIC_INFO b on M.TERMINAL_ID = b.C_TIDh6升级版
WHERE M.MILEAGE > 10000 AND M.OIL_COST > 3000 AND B.C_USE_TYPE IS NOT NULL
GROUP BY B.C_USE_TYPE;
group by后添加vin码,会查询出所有车的信息,不符合需求;
⽅案⼀:
借助 WITH AS 查询语句进⾏查询;
WITH TEMP AS (SELECT B.C_VIN_8 VIN8, S.TOTAL_MILEAGE COUNT, B.C_USE_TYPE TP FROM
IOV_SCREEN_RECORD_UPDATE S LEFT JOIN
ANALYSIS.IOV_CAR_BASIC_INFO B ON S.TERMINAL_ID = B.C_TID)
SELECT * FROM TEMP WHERE TEMP.COUNT IN (SELECT MAX(TO_NUMBER(TEMP.COUNT)) FROM TEMP WHERE TEMP.TP IS NOT NULL GROUP BY TEMP.TP);
注意:如果分组字段中的最⼩值存在重复,⼀个分组,in 条件会查询出多条数据;
⽅案⼆:
使⽤分析函数row_number() over(partition by 分组字段 order by 排序字段)
先把需要的数据查询到第⼀位,再把分组后的第⼀条数据取出即可;
本田cbr23SELECT VIN8, TP, COUNT FROM (SELECT M.TOTAL_MILEAGE COUNT, B.C_VIN_8 VIN8,B.C_USE_TYPE TP, ROW_NUMBER() OVER(
PARTITION BY B.C_USE_TYPE ORDER BY TO_NUMBER(M.TOTAL_MILEAGE) DESC NULLS LAST) RN FROM IOV_SCREEN_RECORD_UPDATE M
LEFT JOIN ANALYSIS.IOV_CAR_BASIC_INFO B ON M.TERMINAL_ID = B.C_TID
器WHERE B.C_USE_TYPE IS NOT NULL)
WHERE RN =1;
汽车安全气囊价格⽅案三:
存储过程
如果返回多条数据,需要⽤到游标;
综上所述,第⼆种⽅案最简单,推荐使⽤;
12122救援收费标准谢谢!
发布评论