访问SQL-计算表2中表1中表1的不同月份

时间:2016-12-08 16:33:48

标签: sql ms-access

我有一个表(订单),其中包含CustomerID,产品,销售和日期(yyyy-mm-dd)。

CustomerID链接到CustomerName上的Customer表。 Customer表包含Customername,City,State,Country。字段。

我想计算每个城市订购的日历年的独特月份数。

不幸的是,因为我只能在所有客户和日期中计算不同的月份。如何将其绑定到Customer表中的每个城市?

SELECT Count(*) AS CountOfMonths
FROM (
SELECT DISTINCT Month(Date), Year(Date)
FROM Orders );

谢谢!

2 个答案:

答案 0 :(得分:0)

这样的事情:

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;

答案 1 :(得分:0)

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

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)。所以你需要一个独特的子查询:

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;