SQL Server左连接计数

时间:2017-12-08 11:28:59

标签: sql sql-server

我有这个示例代码

create table #Reservation
(id int identity(1,1),
 name varchar(50)
);

create table #Reservation_details
(id int identity(1,1),
 reservation_id int,
 reservation_date date,
 seated tinyint
);

create table #Payment
(id int identity(1,1),
 reservation_id int,
 payment decimal(18,2)
);

insert into #Reservation(name)
values ('Spiderman'),('Superman'),('Batman'),('Hulk');

insert into #Reservation_details(reservation_id,reservation_date,seated)
values (1,'2017-12-07',0),(2,'2017-12-08',0),(3,'2017-12-08',1),(4,'2017-12-08',0);

insert into #Payment(reservation_id,payment)
values(1,220),(2,1000)

select
 A.id,
 A.name,
 B.reservation_date,
 B.seated,
 C.payment
from #Reservation A
inner join #Reservation_details B
on B.reservation_id = A.id
left join #Payment C
on C.reservation_id = B.reservation_id
where reservation_date = '2017-12-08'

drop table #Reservation
drop table #Reservation_details
drop table #Payment

我想知道所有预订的日期是' 2017-12-08'并且座位= 1或付款不为空

我已经尝试过将日期放在哪里' 2017-12-08'和坐着= 1或付款不是 null

但相反它向我展示了过去的日期也是如何使用在哪里作为计数?

2 个答案:

答案 0 :(得分:2)

试试吧

select COUNT(*)
from #Reservation A
inner join #Reservation_details B on B.reservation_id = A.id
left join #Payment C on C.reservation_id = B.reservation_id
where reservation_date = '2017-12-08'
  and (B.seated=1 or C.payment is not null)

我认为您忘记使用括号(condition1 OR condition2)进行OR操作。

请参阅运算符优先级 - https://docs.microsoft.com/en-us/sql/t-sql/language-elements/operator-precedence-transact-sql

在您的情况下,如果您不使用括号,那么

reservation_date = '2017-12-08' and B.seated=1 or C.payment is not null

等于以下

(reservation_date = '2017-12-08' and B.seated=1) or C.payment is not null

答案 1 :(得分:1)

select
A.id,
A.name,
B.reservation_date,
B.seated,
C.payment
from (#Reservation A
inner join #Reservation_details B
on B.reservation_id = A.id
left join #Payment C
on C.reservation_id = B.reservation_id)
where B.reservation_date = '2017-12-08'
AND (B.seated =1 or  C.payment is null)

你可以在WHERE子句中使用HAVING来使用COUNT函数,它应该是最后一个语句并且在GROUP BY子句之后