[英]How could I form a tsql query with 'and' and 'not' for a result
我有以下問題:
對於每個城市,顯示僅租用“ Toyota”或“ BMW”類型的汽車而從未租用“ Mercedes”的客戶數量
下表如下:
Car [CarId int, type varchar(30)]
Client [ClientId int, CityId int, Name varchar(30)]
City [CityId int, CityName varchar(30)]
Rent [CarId int, ClientId int, days_number int]
我不知道該如何制定這個查詢,但我一直沒有嘗試。
select city.cityname, count(*) as cnt
from client
join city
on client.cityId = city.cityId
where exists(select * from rent join car on rent.carid = car.carid
where client.clientid = rent.clientid
and car.[type] in ('Toyota', 'BMW'))
and not exists(select * from rent join car on rent.carid = car.carid
where client.clientid = rent.clientid
and car.[type] = 'Mercedes')
group by city.cityname
聲明@ count1 int,@ count2 int
選擇@ count1 = Count(*)
從客戶內部加入租金
在Client.ClientId = Rent.ClientId上
內聯車
在Car.CarId = Rent.CarId上
其中Car.type In('Toyota','BMW')
- 除了
選擇@ count2 = Count(*)
從客戶內部加入租金
在Client.ClientId = Rent.ClientId上
內聯車
在Car.CarId = Rent.CarId上
其中Car.type ='Merccedes'
選擇(@ count1-@ count2)
請看一下這個查詢:
select
City.CityName,
count(1) as NumberOfClients
from
City
inner join Client on City.CityID = Client.CityID
inner join
(
select Rent.ClientID
from
Rent
inner join Car on Rent.CarID = Car.CarID
and Car.type in ('Toyota','BMW','Mercedes')
group by Rent.ClientID
having sum(case when Car.type in ('Toyota','BMW') then 1 else 0 end) > 0
and sum(case when Car.type in ('Mercedes') then 1 else 0 end) = 0
) as Summary
on Client.ClientID = Summary.ClientID
group by
City.CityID,
City.CityName
它的作用是:
在子查詢(名為Summary
)中,選擇所有不同的客戶,條件是這些客戶至少租了一次“ Toyota”或“ BMW”,而從未租過“ Mercedes”。
外部查詢采用子查詢的結果,並計算每個城市的總數。
這可能可以更有效地完成-但這是我首先想到的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.