我相信一定有一种简单的方法可以做到这一点,但我已经把头发扯了几个小时了,但一无所获。这是来自客户列表实用程序的工作查询:

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 子句,但这最终会从输出中删除所有实时预订为零的客户。

最佳答案

也许我没有得到它,但你为什么不使用:

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;

关于sql - 相关记录的条件计数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4059983/

10-10 16:18