数据库是Oracle数据库
很久没有碰sql语句了,今天突然有个需求要这样的sql,还要请教高手赐教啊一个表table1中有id,人名name
id  name
1   张三
2   李四
3   王五
4   小明
5   小红另外一张表table2 中有id,关联res_id,编号code,花费cost,收益receive,时间createdate1  1   500   200   334  2010-01-02
2  1   344   300   444  2010-02-02
3  1   236   560   567  2010-01-12
4  2   1123  540   234  2010-03-02
5  2   1565  700   500  2010-01-12
6  4   556   800   500  2010-01-11
7  5   96    100   234  2010-01-02
8  3   22    200   500  2010-01-15
9  1   5     400   454  2010-01-02
10 5   2223  400   500  2010-01-22
11 2   222   500   234  2010-01-21
12 4   233   600   500  2010-01-25
13 3   223   800   234  2010-03-27
14 3   223   300   500  2010-01-31要求1.查询一月份的所有人的消费
要求2.查询结果是这个样子的张三  李四  王五  小明  小红
200   700   200    800  100
560   500   300    600  500
400   null  null   null null结果这样
请问高手们不吝赐教。谢谢了啊

解决方案 »

  1.   

    select substrb(to_char(createdate,'yyyy-mm-dd'),6,2) d,t1.name,t2.cost from table1 t1,table2 t2 where t1.id = t2.resid and d = '01';
    看这个行不.  我没运行
      

  2.   

    至于说你那个格式, 你去google搜下行列转换看看.!这个我就不给你整了.!
      

  3.   

    行列转换的通用过程 by wildwave
    http://topic.csdn.net/u/20100109/13/6a10c168-f190-4766-b838-adbf03c4ac7b.html?64786
      

  4.   

     sql server 2005 以上版本 我倒是知道怎么实现,oracle 貌似我以前有个同事也遇到了,但后来还是无赖的在业务层处理数据,封装!
      

  5.   

    小红的花费应该是100,400
    select a.name, b.cost
      from table1 a, table2 b
     where a.id = b.res_id
       and to_char(b.createdate, 'YYYYMM') = '201001';
    运行结果:
             Name    Cost
    1 张三 200
    2 张三 560
    3 张三 400
    4 李四 700
    5 李四 500
    6 王五 200
    7 王五 300
    8 小明 800
    9 小明 600
    10 小红 100
    11 小红 400
      

  6.   

    select cost,
    max(case a.name when '张三' then b.cost end) as '张三',
    max(case a.name when '李四' then b.cost end) as '李四',
    max(case a.name when '王五' then b.cost end) as '王五',
    max(case a.name when '小明' then b.cost end) as '小明',
    max(case a.name when '小红' then b.cost end) as '小红'
    from
    (select a.name, b.cost
      from table1 a, table2 b
     where a.id = b.res_id
      and to_char(b.createdate, 'YYYYMM') = '201001')
    group by cost