SELECT GUEST.FIRSTNAME,GUEST.LASTNAME, CHARGETYPE.DESCRIPTION
FROM GUEST
INNER JOIN CHARGES
ON GUEST.GUESTID = CHARGES.GUESTID
INNER JOIN CHARGETYPE
ON CHARGETYPE.CHARGEID = CHARGES.CHARGEID
WHERE CHARGES.CHARGEID IN ('07','03' );
-DEAN JOHNSON晚餐服务
-DEAN JOHNSON晚餐服务
-JANE ADAMS晚餐服务
-PETER ADAMS晚餐服务
-PETER ADAMS晚餐服务
-JOHN SMITH晚餐服务
-JOHN SMITH晚餐服务
-DEAN JOHNSON ATHLETIC CHARGE
-JOHN SMITH ATHLETIC CHARGE
输出应该只显示DEAN和JOHN有运动和晚餐服务费。有没有简单的方法来解决这个问题?
答案 0 :(得分:2)
在count(distinct col)
子句中使用having
:
select
guest.firstname
, guest.lastname
from guest
inner join charges
on guest.guestid = charges.guestid
inner join chargetype
on chargetype.chargeid = charges.chargeid
where charges.chargeid in ('07', '03')
group by
guest.firstname
, guest.lastname
having count(distinct charges.chargeid) = 2;
答案 1 :(得分:0)
使用复制连接非常简单
SELECT
GUEST.FIRSTNAME,
GUEST.LASTNAME,
CHARGETYPE.DESCRIPTION
FROM GUEST
INNER JOIN CHARGES
ON GUEST.GUESTID = CHARGES.GUESTID
INNER JOIN CHARGETYPE c1
ON c1.CHARGEID = CHARGES.CHARGEID
and c1.CHARGEID = '07'
INNER JOIN CHARGETYPE c2
ON c2.CHARGEID = CHARGES.CHARGEID
and c2.CHARGEID = '03'
答案 2 :(得分:0)
我会为此添加一个案例,如果需要,您可以将其用作子查询,以过滤到那些有hadDinner = 1和isAnAthlete = 1的那些:
SELECT GUEST.FIRSTNAME
,GUEST.LASTNAME
, sum(case when CHARGETYPE.DESCRIPTION = 'DINNER SERVICE' then 1 else 0 end) hadDinner
, sum(case when CHARGETYPE.DESCRIPTION = 'ATHLETIC CHARGE' then 1 else 0 end) isAnAthlete
FROM GUEST
INNER JOIN CHARGES
ON GUEST.GUESTID = CHARGES.GUESTID
INNER JOIN CHARGETYPE
ON CHARGETYPE.CHARGEID = CHARGES.CHARGEID
WHERE CHARGES.CHARGEID IN ('07','03' )
Group by GUEST.FIRSTNAME
,GUEST.LASTNAME;