有几条这样的数据,id , date  , shop , y_com ,    total1    01      北京      运输公司1   4
2    01      北京      运输公司2   5
3    01      北京      运输公司3   6
4    01      北京      运输公司1   7
5    01      北京      运输公司1   8
6    01      北京      运输公司1   9
7    01      北京      运输公司1   10查询出来以后成一条这样的数据
  
1     01      北京    运输公司1  (台数38)   运输公司2  (台数5)  运输公司3  (台数6)不知道sql语句能不能做出来,用存储过程也可以,注意台数能自动累加哦!

解决方案 »

  1.   

    select date,shop,
    (case when y_com='运输公司1' then total else 0 end) 运输公司1,
    (case when y_com='运输公司2' then total else 0 end) 运输公司3,
    (case when y_com='运输公司2' then total else 0 end) 运输公司3
    from tb
    group by date,shop
      

  2.   

    select date,shop,
    '运输公司1' as y_com1,sum(decode(y_com,'运输公司1',total ,0)),
    '运输公司2' as y_com1,sum(decode(y_com,'运输公司2',total ,0)),
    '运输公司3' as y_com1,sum(decode(y_com,'运输公司3',total ,0)),from tb
    group by date,shop 
      

  3.   

    --测试数据
    create table test1(id int,cdate varchar2(2),shop varchar2(100), y_com varchar2(100),    total int);insert into test1
    select 1,'01','北京','运输公司1',4 from dual union all
    select 2,'01','北京','运输公司2',5 from dual union all
    select 3,'01','北京','运输公司3',6 from dual union all
    select 4,'01','北京','运输公司1',7 from dual union all
    select 5,'01','北京','运输公司1',8 from dual union all
    select 6,'01','北京','运输公司1',9 from dual union all
    select 7,'01','北京','运输公司1',10  from dual;
    --行列转换
    create or replace procedure getRstData( rst out sys_refcursor)
    is
    begin
    declare
    cursor cur is select y_com,sum(total) s
    from test1 
    group by cdate,shop,y_com;t1 varchar2(100);
    t2 varchar2(100);
    str varchar2(4000);
    begin
    str:='select cdate,shop';
    open cur;
    loop
    fetch cur into t1,t2;
    exit when cur%notfound;
    str:=str||','''||t1||''',''(台数'||t2||')''';
    end loop;
    str:=str||' from test1 group by cdate,shop';
    --dbms_output.put_line(str);
    close cur;
    open rst for str;
    end;
    end;
    --输出结果
    1 01 北京 运输公司1 (台数38) 运输公司2 (台数5) 运输公司3 (台数6)
      

  4.   

    上面几位用SQL写的怎么查不出一条?是多条呢?我就要一条数据就能反应出同一销售店的所有信息,
      

  5.   

    SELECT DATE1,SHOP,'运输公司1 (台数'||SUM(CASE WHEN Y_COM='运输公司1'
    THEN TOTAL ELSE 0 END)||')' 运输公司1,
    '运输公司2 (台数'||SUM(CASE WHEN Y_COM='运输公司2'
    THEN TOTAL ELSE 0 END)||')' 运输公司2,
    '运输公司3 (台数'||SUM(CASE WHEN Y_COM='运输公司3'
    THEN TOTAL ELSE 0 END)||')' 运输公司3 
      FROM A GROUP BY DATE1,SHOP--
        DATE1 SHOP 运输公司1 运输公司2 运输公司3
    1 01 北京 运输公司1 (台数38) 运输公司2 (台数5) 运输公司3 (台数6)
      

  6.   

    case when 語句,Decode()函數都可以實現你的要求.
      

  7.   

    select date,shop, 
    (case when y_com='运输公司1' then total else 0 end) 运输公司1, 
    (case when y_com='运输公司2' then total else 0 end) 运输公司3, 
    (case when y_com='运输公司2' then total else 0 end) 运输公司3 
    from tb 
    group by date,shop,y_com