繁体   English   中英

我怎么能用'and'和'not'组成一个tsql查询结果

[英]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

它的作用是:

  1. 在子查询(名为Summary )中,选择所有不同的客户,条件是这些客户至少租了一次“ Toyota”或“ BMW”,而从未租过“ Mercedes”。

  2. 外部查询采用子查询的结果,并计算每个城市的总数。

这可能可以更有效地完成-但这是我首先想到的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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