根据订单数量选择行

Selecting rows based on a number of orders

我的 table PURCHASES 有以下列:NAME, ORDER_ID, ITEM_ID.

当客户订购2件商品时,在相同ORDER_ID和两个相同或不同ITEM_ID下记录2行(取决于客户是否购买了相同的商品)。

我想select所有订单少于3件且商品少于4件的客户(无论它们是否相同)。这是当前代码:

SELECT NAME, COUNT(DISTINCT ORDER_ID) AS number_of_orders, COUNT(ITEM_ID) AS number_of_items
FROM `PURCHASES`
WHERE number_of_orders <3
AND number_of_items <4
GROUP BY NAME
ORDER BY number_of_items DESC

我收到以下错误消息:Unknown column 'number_of_orders' in 'where clause'

你应该用子查询来做

SELECT * FROM (
  SELECT NAME, COUNT(DISTINCT ORDER_ID) AS number_of_orders, COUNT(ITEM_ID)   AS number_of_items)
FROM `PURCHASES`
WHERE number_of_orders <3
    AND number_of_items <4
GROUP BY NAME
ORDER BY number_of_items DESC

使用这个查询

SELECT NAME, COUNT(DISTINCT ORDER_ID) AS number_of_orders, COUNT(ITEM_ID) AS
number_of_items
FROM `PURCHASES`
GROUP BY NAME
HAving COUNT(DISTINCT ORDER_ID) <3
AND COUNT(ITEM_ID) <4
ORDER BY number_of_items DESC