首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Access SQL-表2中按城市计算的月数与表1不同

问Access SQL-表2中按城市计算的月数与表1不同
EN

Stack Overflow用户
提问于 2016-12-08 16:33:47
回答 2查看 177关注 0票数 0

我有一张桌子(订单),上面有CustomerID,产品,销售和日期(Yyyy)。

CustomerID链接到CustomerName的Customer表。Customer表有Customername、City、State、Country字段。

我想数一数每个城市订购的日历年的唯一月份数。

不幸的是,因为我只能统计所有客户和日期的不同月份。我怎样才能把它绑到顾客餐桌上的每一个城市?

代码语言:javascript
复制
SELECT Count(*) AS CountOfMonths
FROM (
SELECT DISTINCT Month(Date), Year(Date)
FROM Orders );

谢谢!

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-12-08 16:37:06

就像这样:

代码语言:javascript
复制
select country, city, state,
       count(*) as NumDistinctMonths
from (select c.country, c.state, c.city,
             year(o.date) as yyyy, month(o.date) as mm, count(*) as cnt
      from orders as o inner join
           customers as c
           on o.CustomerID = c.CustomerId
      group by c.country, c.state, c.city, year(o.date), month(o.date)
     ) as ccsym
group by country, city, state;
票数 0
EN

Stack Overflow用户

发布于 2016-12-08 16:44:09

只需按年份和城市加入表格和汇总,并计算不同的月份:

代码语言:javascript
复制
select c.country, c.state, c.city, year(o.date), count(distinct month(o.date))
from orders o
join customers c on c.customername = o.customerid
group by c.country, c.state, c.city, year(o.date)
order by c.country, c.state, c.city, year(o.date);

添加一个WHERE子句,如果您只想看到一年。

更新: MS Access不支持COUNT(DISTINCT expresssion)。因此,您需要一个独立的子查询:

代码语言:javascript
复制
select c.country, c.state, c.city, order_year, count(*)
from
(
  select distinct c.country, c.state, c.city, year(o.date) as order_year, month(o.date)
  from orders o
  join customers c on c.customername = o.customerid
) as dist_months
group by country, state, city, order_year
order by country, state, city, order_year;
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/41044367

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档