当前位置: 代码迷 >> Oracle开发 >> 求一查询SQL,请帮忙
  详细解决方案

求一查询SQL,请帮忙

热度:107   发布时间:2016-04-24 07:44:55.0
求一查询SQL,请各位高手帮忙
现有一张数据表Table,其中有3个Int型的列,这3列的值只可能为-1、0以及NULL。现在假设三列的对应关系为:Col1->部门1,Col2->部门2,Col3->部门3。对于该数据表中的记录,通过SQL语句查询出如下格式的结果:

Col1 Col2 Col3 Result
-1 -1 -1 部门1/部门2/部门3
-1 -1 0 部门1/部门2
-1 -1 NULL 部门1/部门2
-1 0 0 部门1
-1 NULL 0 部门1
……

也就是说,查询结果为3列中值为“-1”的所有部门名称,并且以“/”进行分隔;若该列的值不为“-1”,则其对应的部门名称不显示在结果字符串里。小弟卡在这里半天了,希望各位高人能给小弟些提示,感激不尽!

------解决方案--------------------
SQL code
你在修改一下就可以了,方法就是这样--测试数据create table t2(Col1 int,Col2 int,Col3 int)insert into t2 select -1,-1,-1 from dual union allselect -1,-1,0 from dual union allselect -1,0,0 from dual union all select -1,-1,null from dual union allselect -1,null,0 from dual;--执行查询select substr(t.s,1,length(s)-1) from(select  decode(col1,-1,col1||'\','')||decode(col2,-1,col2||'\','')||decode(col3,-1,col3||'\','') s from t2  )t--查询结果1    -1\-1\-12    -1\-13    -14    -1\-15    -1
------解决方案--------------------
就一句话,还不用子查询 
原始表
select * from [tablename] d; 

 -1 -1 0
 -1 0 null
 0 -1 null
 -1 null null
 -1 -1 -1

结果:
Select d.*,substr(Case d.Col1 When -1 Then '/部门1 'End ¦ ¦ Case d.Col2 When -1 Then '/部门2 'End ¦ ¦ Case d.Col3 When -1 Then '/部门3 'End,2) From [tablename] d; 



 -1 -1 0 部门1/部门2 
 -1 0 null 部门1 
 0 -1 null 部门2 
 -1 null null 部门3 
 -1 -1 -1 部门1/部门2/部门3 
  相关解决方案