我正在尝试查询我的SQL数据库,以获取每个客户在特定日期范围内下达的订单数量。
我有一份订单清单如下
CustomerName ClientID DateOrdered
Customer No.2 10 2011-11-25
Customer No.3 11 2011-10-15
Customer No.3 11 2011-11-25
我希望能够找出特定客户在2011-11-1和2011-11-30之间订了多少订单,这应该会导致:
CustomerName ClientID Number
Customer No.3 11 1
Customer No.2 10 1
到目前为止,我已经设法得到了这个
SELECT CustomerName, ClientID, COUNT(*) AS Number
FROM Orders t
GROUP BY CustomerName, ClientID
HAVING COUNT(*) =
(SELECT MAX(Number)
FROM
(SELECT CustomerName, ClientID, COUNT(*) AS Number
FROM Orders
GROUP BY CustomerName, ClientID ) x
WHERE CustomerName = t.CustomerName )
这给了我客户所做的每一笔订单
CustomerName ClientID Number
Customer No.3 11 2
Customer No.2 10 1
我是否正确地解决这个问题,或者是否有一种我完全忽视的简单方法!
答案 0 :(得分:6)
select CustomerName, ClientID, count(*)
from
(
select CustomerName, ClientID
from Orders
where datediff(mm, DateOrdered, getdate()) <= 1
)a
group by CustomerName, ClientID
这样做的好处是利用一个子查询来按行给定月份的日期过滤行(这似乎是你要找的东西)。然后按CustomerName
和ClientID
进行分组,获取订单总和。
答案 1 :(得分:5)
应该可以正常工作:
select CustomerName, ClientID, count(*) as Number
from Orders
where DateOrdered between '20111101' and '20111130'
group by CustomerName, ClientID
答案 2 :(得分:1)
select ClientID, max(CustomerName), count(*)
from Orders
where DateOrdered between '2011-11-01' and '2011-11-30'
group by ClientID
根据数据库的不同,DateOrdered选择的语法可能需要改变。
答案 3 :(得分:0)
SELECT
c.CustomerName,
count(o.OrderID) as Orders
FROM
orders o
JOIN clients c ON o.ClientID = c.ClientID
WHERE
o.DateOrdered BETWEEN '2011-11-01' AND '2011-11-20'
GROUP BY c.ClientID ;