我有来自customer_id的CUSTOMERS和ORDERS表。 我只想获得每个客户下订单数量的计数。 我在这个例子中取得了成功sqlfiddle
但是,记录集很大,我只想让每个客户的记录总数限制为最近有这个数字变化的记录。一种可能的解决方案,列出在过去30天内下订单的所有客户,并列出他们订购的订单总数。
我尝试了一种方法other SQL fiddle。我正在尝试选择前三名客户及其订单总数,按订单日期排序。 这不起作用,仅显示每个客户在截断的时间段内下达的订单数量。
答案 0 :(得分:1)
我认为您对SELECT TOP (3)
和ORDER BY
感到有些困惑。
使用其他WHERE
子句继续初始查询;
SELECT customer_id, COUNT(order_id) AS num_orders
FROM Customers
LEFT JOIN Orders ON (customer_id = cust_id)
WHERE order_date > DATE() - 30 // or desired equivalent
GROUP BY customer_id;
修改
根据您的最新评论...
SELECT customer_id, COUNT(order_id) AS num_orders
FROM Customers
LEFT JOIN Orders ON (customer_id = cust_id)
WHERE customer_id IN(SELECT TOP (3) [cust_id] FROM Orders ORDER BY [order_date] DESC)
GROUP BY customer_id
这将选择最近三个订单的ID并返回每个关联客户的订单总数。
答案 1 :(得分:1)
“SELECT TOP 3客户及其订单总数,按订单日期排序”
为了根据订单数量获得TOP 3
客户,您首先需要"ORDER BY num_orders DESC"
。如果多个客户的订单数量排名第三,则customer_id
中包含ORDER BY
作为平局。
SELECT TOP 3
sub.customer_id,
sub.num_orders,
sub.last_order_date
FROM
(
SELECT
c.customer_id,
Count(o.order_id) AS num_orders,
Max(o.order_date) AS last_order_date
FROM
Customers AS c
LEFT JOIN Orders AS o
ON c.customer_id = o.cust_id
WHERE o.order_date > Date() - 30
GROUP BY c.customer_id
) AS sub
ORDER BY 2 DESC, 1;
这应该会给你前三名客户。如果您希望看到它们按last_order_date
排序,请在子查询中使用该sql并将ORDER BY last_order_date
应用于子查询结果集。
根据您的评论,前3位客户是指最近下订单的3位客户。这实际上是一个更简单的查询,因为ORDER BY
和最终排序顺序只需要一个TOP 3
。将上述查询中的ORDER BY
更改为此...
ORDER BY 3 DESC, 1;
如果num_orders
应该是客户自开始时间以来所下的订单数量 - 即不仅仅是过去30天内的订单 - 将此查询保存为 Query1 :
SELECT TOP 3
sub.cust_id,
sub.last_order_date
FROM
(
FROM Orders AS o
WHERE o.order_date > Date() - 30
GROUP BY o.cust_id
) AS sub
ORDER BY 2 DESC, 1;
然后将此查询保存为 Query2 :
SELECT
o.cust_id,
Count(o.order_id) AS num_orders
FROM Orders AS o
GROUP BY o.cust_id;
最后创建第三个查询,其内部连接 Query1 与 Query2 : Query1 为您提供最近的3个客户及其最后的日期订购; Query2 为您提供每个客户下达的所有订单的总数; INNER JOIN
将 Query2 返回的行仅过滤到 Query1 中的客户。