日期:2014-05-16  浏览次数:20736 次

统计两行给定记录之间的数据
SQL code

-- PostgreSQL V9.04

create table managecard (
    id serial,
    managecard char(18) not null
);

insert into managecard(managecard) values ('207999900100000020');
insert into managecard(managecard) values ('207999900100000021');
insert into managecard(managecard) values ('207999900100000022');

create table trans (
    id serial, 
  card char(18) not NULl,
  transtype char(10) not null,
  transtime char(6)
);

insert into trans (card, transtype, transtime ) values ('207999900100000026', '消费', '050000');
insert into trans (card, transtype, transtime ) values ('207999900100000020', '消费', '050100');
insert into trans (card, transtype, transtime ) values ('207999900100000023', '存款', '050200');
insert into trans (card, transtype, transtime ) values ('207999900100000024', '积分消费', '050300');
insert into trans (card, transtype, transtime ) values ('207999900100000022', '启用', '050400');
insert into trans (card, transtype, transtime ) values ('207999900100000026', '消费', '050500');
insert into trans (card, transtype, transtime ) values ('207999900100000023', '积分消费', '050600');
insert into trans (card, transtype, transtime ) values ('207999900100000021', '消费', '050700');
insert into trans (card, transtype, transtime ) values ('207999900100000020', '积分消费', '050800');
insert into trans (card, transtype, transtime ) values ('207999900100000021', '消费', '050900');
insert into trans (card, transtype, transtime ) values ('207999900100000023', '启用', '051000');


/*
  过程:
 从trans表第一条记录a开始,如果a的卡号在managecard表中存在,则此条数据其后
 的各条数据的卡号都记录在a的卡号旗下,直到遇到下一条卡号在managecard中存在的记录b
 b记录其后的各条数据的卡号都记录在b的卡号旗下,直到遇到下一条卡号在managecard中存在的数据记录c...,
 如此往复。

  根据以上数据及需求得出的结果应该是:
  managecard          card                transtype   transtime 
  -------------------------------
  207999900100000020  207999900100000023  存款        050200
  207999900100000020  207999900100000024  积分消费    050300
  207999900100000022  207999900100000026  消费        050500
  207999900100000022  207999900100000023  积分消费    050600
  207999900100000021  207999900100000023  启用        051000
*/


  小弟不才,能想到的办法只能是一条条检查记录,但是数据量大时肯定不是一个好方法,所以请问有没有更好的办法?

------解决方案--------------------
没有更好的办法。 只能使用程序或者存储过程的办法一条条处理。