我的表格PURCHASES
包含以下列:NAME
,ORDER_ID
,ITEM_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'
答案 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