我有一个汽车表和用户表,存储汽车和用户特定.和一个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;
Run Code Online (Sandbox Code Playgroud)
如何修改sql语句,以便返回租车次数超过2次的用户记录.对不起,请让我公开,它只返回一条记录,我需要列出记录详细信息.我的意思是例如用户A租用CarA和CarB所以在rentrecord表中应该有2行数据,我需要检索这2行数据.对不起,有点暧昧.
任何车辆租两次或更多次:
select userID,COUNT(*)
from rentRecord
group by userID
having COUNT(*) > 2
Run Code Online (Sandbox Code Playgroud)
租了一辆特定车两次或两次以上:
select userID,carID,COUNT(*)
from rentRecord
group by userID,carID
having COUNT(*) > 2
Run Code Online (Sandbox Code Playgroud)
租用一辆特定的汽车(明显的单车类型)两次或更多次,附加数据:
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
Run Code Online (Sandbox Code Playgroud)
基于编辑 - 返回租用多辆汽车的用户的所有租赁信息:
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)
Run Code Online (Sandbox Code Playgroud)
我使用了下面的表,因为我们目前没有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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5541 次 |
| 最近记录: |