关于使用hibernate的系统中的数据统计问题。
有一个交易纪录表,id 买方名(b) 买方名(s)。有一个user表 用户id 用户名,user既可以是买方也可以是卖方。我想统计 所有参与了买卖的人,每个人买了几次,卖了几次。
不考虑运行效率也行,只要能实现。
实际问题是
要对这个表的3个字段按照用户进行统计,因为用户纪录的是id,还要取得用户的name用来现实。
------解决方案--------------------user: id, name
trade: id buyer seller
select a.id, a.name,
(select count(b.id) from trade b where b.buyer = a.id) as buy_times,
(select count(c.id) from trade c where c.seller = a.id) as sell_times
from user a;
group by a.id
------解决方案--------------------hb的映射对于保存用聚合函数出来的值不方便,我一般都是直接sql查,完了用HashMap保存结果,这点hb没有Ibatis方便
------解决方案--------------------create table users
(
uid int not null primary key,
uname varchar(10)
)
go
create table trade
(
tid int not null primary key,
buyuserid int not null,
selluserid int not null
)
go
alter table trade add constraint FK_buyuserid foreign key(buyuserid) references users(uid);
alter table trade add constraint FK_selluserid foreign key(selluserid) references users(uid);
go
insert into users values(1, 'aaa ');
insert into users values(2, 'bbb ');
insert into users values(3, 'ccc ');
insert into users values(4, 'ddd ');
insert into users values(5, 'eee ');
go
insert into trade values(1,1,3);
insert into trade values(2,2,4);
insert into trade values(3,2,3);
insert into trade values(4,3,5);
go
select * from users;
select * from trade;
--买
select count(trade.buyuserid) as buycount,trade.buyuserid,min(users.uname) as buyusername from trade,users where trade.buyuserid=users.uid group by trade.buyuserid;
--卖
select count(trade.selluserid) as sellcount,trade.selluserid,min(users.uname) as sellusername from trade,users where trade.selluserid=users.uid group by trade.selluserid;