SQL语句如何检索具有2个或更多记录的数据?

时间:2011-03-10 14:34:40

标签: sql

我有一个Car表和User表,用于存储汽车和用户特定的信息。和一个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所以在rentrecord表中应该有2行数据,我需要检索这2行数据。对不起,有点暧昧。

2 个答案:

答案 0 :(得分:6)

两次或多次租用任何车辆:

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

答案 1 :(得分:2)

在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