我一直在尝试使用Count distinct来编写基于SQL的查询,但是我遇到了如何正确构建Microsoft Access格式的问题。
我当前的查询采用以下格式,如果可能,我想将Count操作转换为非重复计数:
SELECT
a.Customer_ID, a.First_Name,
COUNT (b.Payment_Method) AS Payment_Method <- would like to get the distinct count
Count (b.Store_Number) as Store_Number <- would like to get the distinct count
SUM (b.Sales_Amount) AS Sales_Amount
FROM Table1 a
INNER JOIN Table2 b ON a.Customer_ID = b.Customer_ID
WHERE (((a.Date_ID) > 1234))
GROUP BY a.Customer_ID, a.First_Name
我熟悉此查询的SQL构造,并希望使用MS-Access重新创建结果。
答案 0 :(得分:1)
这比其他数据库复杂得多,但你可以在加入之前:
SELECT a.Customer_ID, a.First_Name, p.num_pm, s.num_sn, s.sum_sa
FROM (Table1 as a INNER JOIN
(SELECT CustomerId, COUNT(*) as num_pm
FROM (SELECT DISTINCT CustomerId, Payment_Method FROM Table2) as b
GROUP BY CustomerId
) as p
ON a.CustomerId = p.CustomerId
) INNER JOIN
(SELECT CustomerId, COUNT(*) as num_sn, SUM(sa) as sum_sa
FROM (SELECT CustomerId, Store_Number, SUM(Sales_Amount) as sum_sa
FROM Table2
GROUP BY CustomerId, Store_Number
) as b
GROUP BY CustomerId
) as s
ON s.CustomerId = a.CustomerId
WHERE a.Date_ID > 1234