SQL count date range

给你一囗甜甜゛ 提交于 2019-12-11 02:07:33

问题


I'm trying to query my SQL database to get the number of orders made by each client within a certain date range.

I have a list of orders as follows

CustomerName       ClientID        DateOrdered
Customer No.2         10            2011-11-25
Customer No.3         11            2011-10-15
Customer No.3         11            2011-11-25

and I want to be able to find out how many orders have been made by a specific client for example between 2011-11-1 and 2011-11-30, this should result in :

CustomerName       ClientID        Number
Customer No.3         11             1
Customer No.2         10             1

So far I've managed to get this

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 )

Which gives me every order the customer has ever made

CustomerName       ClientID        Number
Customer No.3         11             2
Customer No.2         10             1

Am I going about the right way to solve this or is there a simpler way which I've completely overlooked!


回答1:


select CustomerName, ClientID, count(*)
from
(
    select CustomerName, ClientID
    from Orders
    where datediff(mm, DateOrdered, getdate()) <= 1
 )a
group by CustomerName, ClientID

What this does is utilize a subquery that filters the rows by the dates in a given month (that seems to be what you are looking for). Then it groups by the CustomerName and ClientID and gets the sum of their orders.




回答2:


Should work fine:

select CustomerName, ClientID, count(*) as Number
from Orders
where DateOrdered between '20111101' and '20111130'
group by CustomerName, ClientID



回答3:


select ClientID, max(CustomerName), count(*) 
from Orders 
where DateOrdered between '2011-11-01' and '2011-11-30'
group by ClientID

Depending on database, the syntax of the DateOrdered selection may need to be varied.




回答4:


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 ;


来源:https://stackoverflow.com/questions/8297080/sql-count-date-range

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!