select uid,bid,
借书天数=datediff(day,a.tm,isnull(b.tm,getdate()),
状态=case when b.tm is null then '未还' else '已还' end
(
select uid,bid,tm from t where flag='借'
) a inner join (
select uid,bid,tm from t where flag='借'
) on a.uid=b.uid and a.bid=b.bid
select a.sid,a.uid,a.bid,datediff(d,a.tm,isnull(b.tm,getdate())),b.flag
from t a
left join t b on a.uid=b.uid and a.bid=b.bid and b.flag='还'
where a.flag='借'
and A.sid in (select top 2 sid from 表T where where uid = A.uid and bid = A.bid order by sid)
借了还--借了没还---借了还,还了借,借了还
select A.uid, A.bid, A.tm, B.tm, datediff(day, A.tm, B.tm) 借用多长时间
from 表T A inner join 表T B
on A.uid = B.uid
and A.bid = B.bid
where A.flag = '借'
and B.flag = '还'
and A.sid in (select top 2 sid from 表T where where uid = A.uid and bid = A.bid order by sid)
select a.sid,a.uid,a.bid,datediff(d,a.tm,isnull(b.tm,getdate())),b.flag
from t a
left join t b on a.uid=b.uid and a.bid=b.bid and b.flag='还'
where a.flag='借'
修改一下
select A.uid, A.bid, A.tm, B.tm, datediff(day, A.tm, B.tm) 借用多长时间
from 表T A left join 表T B
on A.uid = B.uid
and A.bid = B.bid
where A.flag = '借'
and B.tm = (select isnull(min(tm),getdate()) from 表T where uid = A.uid and bid = A.bid and flag = '还')
select A.uid, A.bid, A.tm, B.tm, datediff(day, A.tm, B.tm) 借用多长时间
from 表T A left join 表T B
on A.uid = B.uid
and A.bid = B.bid
where A.flag = '借'
and B.flag = '还'
and B.tm = (select min(tm) from 表T where uid = A.uid and bid = A.bid and flag = '还')
可以的.
select a.uid,a.bid,
借书天数=datediff(day,a.tm,isnull(b.tm,getdate())),
状态=case when b.tm is null then '未还' else '已还' end
from
(
select sid=(select sum(1) from t where uid=aa.uid and bid=aa.bid and sid<=aa.sid)
,uid,bid,tm from t aa where flag='借'
) a inner join (
select sid=(select sum(1) from t where uid=aa.uid and bid=aa.bid and sid<=aa.sid)
,uid,bid,tm from t aa where flag='还'
) b on a.uid=b.uid and a.bid=b.bid and a.sid=b.sid
select a.sid,a.uid,a.bid,datediff(借书天数,a.tm,isnull(b.tm,getdate()))
from (select uid, bid, min(tm) from t where flag='借' group by uid,bid) a
left jion
(select uid, bid, min(tm) from t where flag='还' group by uid,bid) b
on a.uid=b.uid and a.bid=b.bid