oracle数据库方法
1、显示指定条数,多余条数汇总
--通过下列语句生成行号PARTITION BY 分段字段 row_number ( ) over ( PARTITION BY ID ORDER BY money DESC ) line, --通过行号大小进行合并查询 UNION ALL 合并两条查询结果 SELECT * FROM( SELECT pageSize AS line,id,org_name,'' AS SECTION_ID,'其他' AS SEOF_NAME,SUM( money) AS money FROM tab WHERE line >= pageSize GROUP BY id,org_name UNION ALL SELECT line,id,org_name,SECTION_ID,SEOF_NAME,money FROM tab WHERE line < pageSize ) ORDER BY id,line
2、nvl()函数巧避空值求和
SUM(nvl( t1.c01, 0 ) + nvl( t1.c02, 0 ) + nvl( t1.c05, 0 ) + nvl( t1.c06, 0 ) + nvl( t1.c07, 0 ) + nvl( t1.c09, 0 ) + nvl( t1.c10, 0 ) + nvl( t1.c11, 0 ) + nvl( t1.c12, 0 ) + nvl( t1.c14, 0 ) + nvl( t1.c19, 0 ) + nvl( t1.c30, 0 ) + nvl( t1.c35, 0 ) + nvl( t1.c98, 0 ) + nvl( t1.c99, 0 ) ) --通过nvl()函数可以在求和的时候避免出现空值
3、lag() over()函数组合实现字段推动
-- r_count 推动字段 1 推动条数(正为向上负为向下) PARTITION BY 分段字段 lag ( r_count, 1 ) over ( PARTITION BY ABC,ORDER BY year_month ASC )
4、decode()和 sign()结合妙用
DECODE(endDate,startDate,to_char(last_day(to_date('endDate','yyyy-mm')),'dd') --decode(条件,值1,返回值1,值2,返回值2,...值n,返回值n,其他) --相当于 IF 条件=值1 THEN RETURN(翻译值1) ELSIF 条件=值2 THEN RETURN(翻译值2) ...... ELSIF 条件=值n THEN RETURN(翻译值n) ELSE RETURN(缺省值) END IF SIGN(a-b) -- 当a-b< 0返回-1当a-b>0返回1当a-b=0返回0 --DECODE 和 SIGN 结合 DECODE (SIGN(a-b),1,大于时的返回结果,0,等于时的返回结果,-1,小于时的返回结果)
5.pivot巧妙行转列
行转列 --CD_SYS_FETY_ID 即要转成列的字段 max(TOTAL_MONEY) 此处必须为聚合函数,in () 对要转成列的每一个值指定一个列名 select * from tab pivot( max(TOTAL_MONEY) for CD_SYS_FETY_ID in ( '0001' AS C0001, '0002' AS C0002, '0003' AS C0003, '0004' AS C0004, '0005' AS C0005 ) )
小白技术分享