简体   繁体   中英

How could I form a tsql query with 'and' and 'not' for a result

I have the following question:

For each city display the number of clients who only rented cars of type 'Toyota' or 'BMW' and never rented 'Mercedes'

The tables are as follows:

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]

I don't know how would I formulate this query I tried hard but nothing worked until now.

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

Declare @count1 int, @count2 int

Select @count1 = Count(*)

From Client inner join Rent

on Client.ClientId = Rent.ClientId

inner join Car

on Car.CarId = Rent.CarId

Where Car.type In( 'Toyota','BMW')

--except

Select @count2 = Count(*)

From Client inner join Rent

on Client.ClientId = Rent.ClientId

inner join Car

on Car.CarId = Rent.CarId

Where Car.type = 'Merccedes'

Select (@count1 - @count2)

Please take a look at this query:

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

What it does is:

  1. In subquery (named Summary ) all distinct clients are selected, basing on a condition that those clients have rented 'Toyota' or 'BMW' at least once, while never have rented 'Mercedes'.

  2. The outer query takes the results of the subquery and calculates totals for each city.

This can probably be done more efficiently - but this is first that comes to my mind.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM