当前位置: 代码迷 >> Oracle开发 >> 求sql大神帮忙解决有关问题,感谢
  详细解决方案

求sql大神帮忙解决有关问题,感谢

热度:183   发布时间:2016-04-24 06:23:46.0
求sql大神帮忙解决问题,感谢~
本帖最后由 yincan2011 于 2015-10-28 17:38:00 编辑
现在有一张表是这样的,4个字段:设备        运行商    数量 日期
sql查询的结果:select  *  from table    where 数量> 100

设备        运行商    数量 
爱国者 mobile 587   
爱国者 other 157  
爱国者 unicom 199
现代 mobile 351
现代 other 122
现代 unicom 140


但是现在要得到这样的结果:
设备        mobile        other unicom
爱国者 587                157   199
现代 351                122           140

问下sql怎么写啊?感觉应该是要写子查询和自连接的?就是设备相同名称分组,运行商的数据分别作为行展示出来,这个sql可以写出来??

分不多了!谢谢大家解答!

------解决思路----------------------
搜索行列转换
------解决思路----------------------
行转列--可以百度研究下行列转换

with tab(设备,
运行商,
数量) as
 (select '爱国者', 'mobile', 587
    from dual
  union all
  select '爱国者', 'other', 157
    from dual
  union all
  select '爱国者', 'unicom', 199
    from dual
  union all
  select '现代', 'mobile', 351
    from dual
  union all
  select '现代', 'other', 122
    from dual
  union all
  select '现代', 'unicom', 140 from dual)

select 设备,
       sum(case
             when 运行商 = 'mobile' then
              数量
             else
              null
           end) mobile,
       sum(case
             when 运行商 = 'other' then
              数量
             else
              null
           end) other,
       sum(case
             when 运行商 = 'unicom' then
              数量
             else
              null
           end) unicom
  from tab
 group by 设备;


------解决思路----------------------
select 设备,
       sum(decode(运行商,'mobile',数量)) mobile,
       sum(decode(运行商,'other',数量)) other,
       sum(decode(运行商,'unicom',数量)) unicom
  from tab
 group by 设备;


case when太累了
  相关解决方案