统计独特客户

时间:2016-10-18 08:08:52

标签: sql ms-access count

提前感谢您的帮助。我一直在研究这个问题好几个小时。我有一个包含以下列的表:

OrderID | CustomerID | Date      | Course
--------|------------|-----------|----------
14954   | 13440      |16.10.2016 | Zürich
14955   | 13441      |17.10.2016 | Bern
14956   | 13441      |17.10.2016 | Aargau
14957   | 13442      |17.10.2016 | Bern
14958   | 10483      |17.10.2016 | Zürich
14959   | 13442      |18.10.2016 | Solothurn

我想计算客户的第一个订单,该订单是在某个特定日期收到的。该查询应该为17.10.2016产生以下结果。

Bern: 2
Aargau: 0
Zürich: 1

我已经尝试过DISTINCT和嵌套查询,如:

SELECT Count(*) AS Anzahl 
FROM   (SELECT DISTINCT kundennummer 
        FROM   (SELECT datum, 
                       kundennummer 
                FROM   unterlagenbestellungen 
                WHERE  kurs LIKE 
       '%" & DgvStatUnterlagenbestellungen.Rows(x).HeaderCell.Value & "%') 
        WHERE  datum BETWEEN # " & mindatum & " # AND # " & maxdatum & " # )

我非常感谢任何帮助

2 个答案:

答案 0 :(得分:0)

  

试试这个:

SELECT 
 cource,
 COUNT(customer_id) 
FROM
 [your table]
WHERE DATE = '2016-06-17' 
GROUP BY cource 
ORDER BY cource 

答案 1 :(得分:0)

这也适用于Access:

SELECT t1.Course, Count(t2.OrderID)
FROM tab AS t1
LEFT JOIN -- get all Courses for that day
 ( -- find the minimum order per customer
   SELECT CustomerID, Min(OrderID) AS OrderID
   FROM tab AS t2
   WHERE Date='17.10.2016'
   GROUP BY CustomerID
 ) AS t2
ON t1.CustomerID = t2.CustomerID 
AND t1.OrderID = t2.OrderID -- only one row per customer
WHERE Date='17.10.2016'
GROUP BY t1.Course