我有一个汽车表和用户表,其中存储汽车和用户的细节。以及RentRecord表,用于存储哪些用户已经租车和日期。我想检索租车超过2次的用户,如何编写sql语句,我尝试使用count和group by,但最终只得到了一行数据。
Select count(rr.userId) as T, userName, carType
from rentrecord rr
inner join user u on u.userId = rr.userId
inner join car c on c.carId = rr.carId
group by (rr.userId) having T>=2; 如何修改sql语句,使其返回租车次数超过2次用户记录。对不起,让我澄清一下,它只返回一条记录,我需要列出记录的详细信息。我的意思是例如用户A租借CarA和CarB,所以在租户记录表中应该有2行数据,我需要检索这2行数据。为模棱两可感到抱歉。
发布于 2011-03-10 22:42:03
租车两次或以上:
select userID,COUNT(*)
from rentRecord
group by userID
having COUNT(*) > 2租了一辆车两次或更多次:
select userID,carID,COUNT(*)
from rentRecord
group by userID,carID
having COUNT(*) > 2租赁了一辆特定的汽车(具有明显的单一车型)两次或更多次,并提供了其他数据:
select userID,username,cartype,Cnt
from (select userID,carID,COUNT(*) as Cnt
from rentRecord
group by userID,carID
having COUNT(*) > 2) multi
inner join
user u
on
multi.userID = u.UserID
inner join
car c
on
multi.carID = c.CarID基于编辑-返回多个租车用户的所有租车信息:
SELECT
* /* TODO - Specify columns */
from
[User] u
inner join
rentRecord rr
on
u.UserID = rr.UserID
inner join
Car c
on
rr.CarID = c.CarID
where
u.UserID in (select UserID from (select userID,COUNT(*) Cnt
from rentRecord
group by userID
having COUNT(*) >= 2) t)我使用了下面的表,因为我们目前还没有来自OP的模式:
create table [User] (
UserID int not null
)
go
insert into [User](UserID)
select 1 union all
select 2
go
create table Car (
CarID int not null
)
go
insert into Car(CarID)
select 1 union all
select 2
go
create table rentRecord (
UserID int not null,
CarID int not null
)
go
insert into rentRecord(UserID,CarID)
select 1,1 union all
select 1,2 union all
select 2,1 union all
select 2,2
go发布于 2011-03-10 22:39:33
在mysql语法中
SELECT
A.id, COUNT(B.id)
FROM userTable A
LEFT JOIN rentRecordTable B on B.user_id_of_rent = A.id
GROUP BY A.id
HAVING COUNT(B.id) > 2 https://stackoverflow.com/questions/5261164
复制相似问题