2016-12-08 2 views
0

私はCustomerID、Product、Sales、およびDate(yyyy-mm-dd)を含む表(注文)を持っています。SQLにアクセス - 表2の都市別に表1の別々の月を数えてください

CustomerIDはCustomerNameのCustomerテーブルにリンクされています。 Customerテーブルには、Customername、City、State、Countryフィールドがあります。

私は、各都市が発注した暦年の唯一の月数を数えたいと思います。

残念ながら、私はすべての顧客と日付の間に別々の月を数えることしかできませんでした。それをCustomerテーブルの各都市にどのように結び付けることができますか?

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

ありがとうございます!このような

答えて

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

これは機能しているようですが、確認する前にいくつかのスポットチェックを行います。暫定的に感謝! – assutu

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; 
+0

何らかの理由で私は 'クエリの式' count(別の月(o.date))で構文エラー(演算子がありません)を取得しています ' – assutu

+0

ああ、MS Accessの多くの欠点のひとつです。私はそれに応じて私の答えを更新しました。 –

関連する問題