按日期对查询进行分组和计数字段

时间:2017-12-05 16:42:34

标签: sql ms-access

我有这样的查询(在MS Access 2016上):

|       City        |  CustomerID  |    OrderID   |   OrderDate   |

|       Venice      |      18      |      45      |   01/01/2015  |
|       Venice      |      18      |      56      |   01/01/2015  |
|       Venice      |      18      |      59      |   03/02/2015  |
|       Venice      |      20      |      60      |   04/02/2015  |
|       Venice      |      20      |      153     |   08/07/2017  |
|        Rome       |      22      |      65      |   05/03/2015  |
|        Rome       |      25      |      68      |   08/03/2015  |
|       Milan       |      27      |      72      |   04/02/2015  |
|       Milan       |      27      |      168     |   04/09/2017  |

我希望按日期过滤结果并获得类似的结果(例如,在2015年1月1日至2016年1月1日期间按OrderDate过滤):

|       City        |  CustomerID  |    OrderID   |
|                   |   (Count)    |     (Count)  |
|       Venice      |      2       |      3       |
|        Rome       |      2       |      2       |
|       Milan       |      1       |      1       |

基本上:

  • 城市字段应选择一次为唯一
  • CustomerID 字段应该选择一次,如果是唯一的并且总结而不同
  • 订单ID 字段应计算在内

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

MS Access不支持count(distinct),但您可以通过两个级别的聚合执行此操作:

select city, count(*) as num_customers, sum(num_orders) as num_orders
from (select city, customerId, count(*) as num_orders
      from <your query here> as t
      group by city, customerId
     ) as t
group by city;