sql高级用法记录

1.case when then 嵌套用法

2.oracle分组排序取最值

select * from 
(select t.*, row_number() over(partition by 分组字段 order by 排序字段 desc ) rn
from tablename t )
where rn=1

3.遍历树结构数据    3.1 案例1:查询应收单发票及其所有的历史废弃发票

select 
   inv.fileid fileID,
   inv.pri_inv_no priInvoiceNo,
   inv.inv_no invoiceNo,
   inv.inv_dt invDt,
   inv.act_frt_hire invoiceAmount,
   case 
     when inv.inv_typ='FREIGHT' then '运费'
     when inv.inv_typ='HIRE' then '租金'
     when inv.inv_typ='DEMURRAGE' then '滞期费'
     when inv.inv_typ='DESPATCH' then '速遣费'
     when inv.inv_typ='OTHER' then '杂费'
   else '' 
   end invType,
   case 
     when inv.inv_status='N' then '正常'
     when inv.inv_status='A' then '废弃'
   else '' 
   end invStatus
from sh_invoice inv             
start with inv_no =(select invoiceno from v_sh_cml_incomemanage where fileid='8ae47aa15a93d392015ac5d173b11a52')
connect by NOCYCLE prior pri_inv_no = inv_no
order by inv.inv_dt desc

  3.2 案例2:查找当前发票及其第一第废弃的发票

               select
               inv.inv_no,inv.pri_inv_no,
               (select distinct inv_no
               from sh_invoice 
               where pri_inv_no is null
               start with inv_no = inv.inv_no
               connect by NOCYCLE prior pri_inv_no = inv_no) firstInvNo
               from sh_invoice inv
               where inv.pri_inv_no is not null
               and inv.inv_status='N'

  3.3 案例3:查询截止到指定时间前最近的一张发票

	        select 						
	          inv_no,						
	          (select distinct inv_no               						
	          from sh_invoice						
	          where rownum=1						
	          and to_char(inv_dt,'yyyy-mm-dd')<='2017-05-17'           						
	          start with inv_no = inv.inv_no               						
	          connect by NOCYCLE prior pri_inv_no = inv_no						
	          ) lastInvNo						
	        from sh_invoice inv						
	        where inv.pri_inv_no is not null						
	        and inv.inv_status='N' 	

4.Decode放在join on条件后、放在where条件后的使用方法 4.1 decode放在join on 条件后

	    left join (     									
	      SELECT *        									
	      FROM (      									
	        SELECT t.*, ROW_NUMBER() OVER (PARTITION BY invoiceno ORDER BY trackdate desc,createdate DESC) AS rn      									
	        FROM sh_inv_track t     									
	        )     									
	        WHERE rn = 1      									
	    ) track on track.invoiceno=decode(inv.pri_inv_no,null,inv.inv_no,firstinv.firstInvNo)

4.2 decode放在where条件后

SELECT A.CHECK_INFORM_NO,A.CHECK_NO,SCAN_NUM,
       B.MODEL_TYPE,B.INTEGRATED_VER,B.INTERNAL_VER
      FROM SFC.PDI_CHECK_HEAD A  
            LEFT JOIN SFC.PDI_CHECK_INFORM_BILL B
           ON B.CHECK_INFORM_NO = A.CHECK_INFORM_NO AND B.ENABLED_FLAG = 'Y' AND B.ORGANIZATION_ID = 31
           WHERE 
           DECODE(B.MODEL_TYPE,'MBB',B.INTEGRATED_VER,B.INTERNAL_VER) = '集成版本'
    原文作者:SQL
    原文地址: https://blog.csdn.net/fenyu8/article/details/70839871
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞