首页 > 学技术 > 技术网文 > DB2 > 正文

[精华] 请教一个sql语句,谢谢


来源 chinaunix.net 酷勤网整理

表结构:
        name               type                  value
               lee                breakfast                10
               lee               lunch                        20
              lee                supper                     20
怎么用一句sql查询出如下结果:
        name            breakfast        lunch          supper
               lee                 10                20                  20



 cyberflying 回复于:2005-07-01 14:37:23

典型的行列转换,case when可以搞定。


 Zerg 回复于:2005-07-01 16:15:57

根据 cyberflying 提示:
with temp ( name,breakfast,lunch,supper) as (
select name,
case type 
     when 'breakfast' then sum(value)
      else null 
      end ,
case type 
     when 'lunch' then sum(value) 
      else null 
     end,
case type 
     when 'supper' then sum(value) 
      else null 
     end from table_test group by name,type
     )
select name,sum(breakfast) as "breakfast",sum(lunch) as "lunch",sum(supper) as "supper" from temp group by name

不知道是不是这样写?


 daliwa 回复于:2005-07-01 21:13:17

呵呵,楼上写得不错!


 cyberflying 回复于:2005-07-02 16:34:40

这样可以简洁些,没必要两次group by吧:)
select name,
          sum(case  type when 'breakfast' then value end) breakfast,
          sum(case  type when 'lunch' then value end) lunch,
          sum(case  type when 'supper' then value end) supper,
  from your_tbl
group by name


 Zerg 回复于:2005-07-03 19:04:37

谢谢cyberflying。如果列value类型非decimal,如date,varchar该sql怎么写?


 rheet1978 回复于:2005-07-04 10:48:14

谢谢cyberflying,收藏


 liugr3988 回复于:2005-07-23 17:22:19

这个问题问得好,现实中经常会遇到这种问题的。


 markmahw 回复于:2005-07-25 02:21:19

顶一下




原文链接:http://bbs.chinaunix.net/viewthread.php?tid=570804
转载请注明作者名及原文出处



收藏本页到: