相关记录的条件计数

时间:2010-10-30 18:03:13

标签: sql ms-access

我确信必须有一个简单的方法来做到这一点,但我现在已经把头发弄了好几个小时,而我却无处可去。以下是来自客户列表实用程序的工作查询:

SELECT c.customer_ID, title, surname, forenames, COUNT(booking_ID) AS bookings
FROM customer c 
LEFT JOIN booking b 
ON c.customer_ID = b.customer_ID
WHERE customer_Live
GROUP BY c.customer_ID, surname, forenames, title
ORDER BY surname;

问题在于:COUNT会返回相关预订的所有。但是预订表有一个'booking_Live'列,只要取消预订,该列就会设置为false。我需要做的是以某种方式将取消的预订从计票中排除;因此,如果所有客户都已取消预订,它将返回0.我已经尝试在该组中添加一个HAVING子句,但这最终会从输出中删除所有没有实时预订的客户。

2 个答案:

答案 0 :(得分:4)

也许我没弄好它,但你为什么不使用:

SELECT c.customer_ID, title, surname, forenames, COUNT(booking_ID) AS bookings
FROM customer c 
LEFT JOIN booking b 
ON (c.customer_ID = b.customer_ID AND b.booking_Live = true)
WHERE customer_Live
GROUP BY c.customer_ID, surname, forenames, title
ORDER BY surname;

答案 1 :(得分:3)

子查询应解决您的问题。这样的事情。

SELECT c.customer_ID, title, surname, forenames, COUNT(booking_ID) AS bookings
FROM customer c 
LEFT JOIN (SELECT customer_ID, booking_id FROM Booking WHERE booking_live = true) as b 
ON c.customer_ID = b.customer_ID
WHERE customer_Live
GROUP BY c.customer_ID, surname, forenames, title
ORDER BY surname;