求教一个类似行列互换的sql语句
xiaohu0901
2008-11-22
求教一个类似行列互换的sql语句!
我现在有张表cityorder,有如下几个列:id,amount,city,date。表中有以下一些记录: id amount city date 1 12 001 08-11-16 2 14 001 08-11-17 3 25 002 08-11-16 4 23 002 08-11-17 我想求教记录按如下方式展示的sql语句???? city 08-11-16 08-11-17 001 12 14 002 25 23 |
|
jayzotion
2008-12-29
SELECT
DISTINCT city,(SELECT TOP 1 amount FROM cityorder WHERE city=a.city AND CONVERT(CHAR(10),date,121)='2008-11-16') AS '08-11-16', (SELECT TOP 1 amount FROM cityorder WHERE city=a.city AND CONVERT(CHAR(10),date,121)='2008-11-17') AS '08-11-17' FROM cityorder a |
|
cosmo2097
2008-12-31
oracle有比较方便的行列互换函数
以下是mysql的方式 select x.city,x.amount1,x.amount2 from(select c.city,Group_concat(if(c.date='08-11-16',c.amount,'') separator '') as 08-11-16,Group_concat(if(c.date='08-11-17',c.amount,'') separator '') as 08-11-17 from cityorder c group by c.city) as x; |
|
xiaohu0901
2009-01-04
谢谢各位,问题已解决!
|
|
brilliant2008
2009-02-04
select
city, (select sum(amount) from cityorder where sdate= to_date('08-11-16','yy-mm-dd')) "08-11-16", (select sum(amount) from cityorder where sdate= to_date('08-11-17','yy-mm-dd')) "08-11-17" from cityorder group by city; 也许这个对你来说更合适 |
|
xiaohu0901
2009-02-08
这种方法只能解决日期数目固定!
|
|
brilliant2008
2009-02-10
那请楼主把代码帖上来,我们大家好学习学习
|
|
xiaohu0901
2009-02-17
主要是通过一个存储过程,动态解决的
create or replace procedure city_orderamount AS sql1 varchar(8000); sql2 varchar(8000); t number(2); CURSOR c_test is select distinct a.statis_date from city_day_statis a where a.statis_date>=(sysdate-6) and a.statis_date<=sysdate order by a.statis_date; begin sql1:='select areaid '; sql2:='select areaid '; for v_test in c_test loop sql2 := sql2 ||', nvl(max(a'||to_char(v_test.statis_date,'yyyymmdd')||'),0) as a'||to_char(v_test.statis_date,'yyyymmdd'); sql1 := sql1 ||','|| 'case when to_char(statis_date,'||chr(39)||'yyyymmdd'||chr(39)||') = '|| chr(39)||to_char(v_test.statis_date,'yyyymmdd')||chr(39)||' then nvl(sum(amount),0) end a' || to_char(v_test.statis_date,'yyyymmdd'); end loop; sql1 := sql1 || ' from city_day_statis where to_char(statis_date,'||chr(39)||'yyyymmdd'||chr(39)||')<='||to_char(sysdate,'yyyymmdd') ||' and to_char(statis_date,'||chr(39)||'yyyymmdd'||chr(39)||')>'||to_char((sysdate-6),'yyyymmdd')||' group by areaid,statis_date'; select count(*) into t from all_all_tables a where a.table_name = 'TEMP_CITY_ORDERAMOUNT'; sql2 := 'create table temp_city_orderamount as '|| sql2||' from ('||sql1||') group by areaid'; dbms_output.put_line(sql2); if t>0 then begin sql1:='drop table temp_city_orderamount '; EXECUTE IMMEDIATE sql1; end ; end if; EXECUTE IMMEDIATE sql2; end ; |