根据许多订单选择行

时间:2015-08-20 20:52:13

标签: select segment orders

我的表格PURCHASES包含以下列:NAMEORDER_IDITEM_ID

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

我想选择总共少于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'

2 个答案:

答案 0 :(得分:0)

您应该使用子查询

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

答案 1 :(得分:0)

使用此查询

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