我在sql方面相对较新,需要一些基本查询结构的帮助。
Problem:根据一组参数从表中检索订单数量和客户id。
我想编写一个查询,以计算每个客户(列: Customerid)下的订单数量,以及订单数量应该大于或等于10并且订单状态应该处于活动状态的CustomerID。此外,我还想知道属于每个customerid的订单的第一个交易日期。
表描述:
product_orders
Orderid CustomerId Transaction_date Status
------- ---------- ---------------- -------
1 23 2-2-10 Active
2 22 2-3-10 Active
3 23 2-3-10 Deleted
4 23 2-3-10 Active我编写的查询:
select count(*), customerid
from product_orders
where status = 'Active'
GROUP BY customerid
ORDER BY customerid;上面的陈述给了我
客户标识下的所有订单之和,但不满足至少10个订单的条件。
。
理想解决方案应该如下所示:
Total Orders CustomerID Transaction Date (the first transaction date)
------------ ---------- ----------------
11 23 1-2-10提前谢谢。希望你们能过来帮我一把。
干杯,
莱昂尼达斯
发布于 2010-04-29 09:37:24
SELECT
COUNT(*) AS [Total Orders],
CustomerID,
MIN(Transaction_date) AS [Transaction Date]
FROM product_orders
WHERE product_orders.Status = 'Active'
GROUP BY
CustomerId
HAVING COUNT(*) >= 10发布于 2010-04-29 09:35:29
HAVING将允许您过滤像COUNT()这样的聚合& MIN()将显示第一次约会。
select
count(*),
customerid,
MIN(order_date)
from product_orders
where status = 'Active'
GROUP BY customerid
HAVING COUNT(*) >= 10
ORDER BY customerid如果您想要最早的日期,而不管状态如何,您可以对其进行子查询。
select
count(*),
customerid,
(SELECT min(order_date) FROM product_orders WHERE product_orders.customerid = p.customerid) AS FirstDate
from product_orders P
where status = 'Active'
GROUP BY customerid
HAVING COUNT(*) >= 10
ORDER BY customerid发布于 2010-04-29 09:36:27
此查询应为每个具有10个或更多活动订单的客户提供活动订单总数。它还将显示第一个活动订单日期。
Select Count(OrderId) as TotalOrders,
CustomerId,
Min(Transaction_Date) as FirstActiveOrder
From Product_Orders
Where [Status] = 'Active'
Group By CustomerId
Having Count(OrderId)>10https://stackoverflow.com/questions/2736158
复制相似问题