I would like to generate a table (or query result) in this form
+---------------------+---------------------+
| Email | Favourite Brand ID |
+---------------------+---------------------+
| customer@gmail.com | 89 |
+- -+- -+
| another@gmail.com | 193 |
+- -+- -+
I have managed to write a query that generates a list of unique brand ID’s with customer email addresses and the number of times that customer has purchased that brand. The results look something like this:
+---------------------+-----------+---------------+
| Email | Brand ID | CountOfOrders |
+---------------------+-----------+---------------+
| customer@gmail.com | 89 | 10 |
+- -+- -+- -+
| another@gmail.com | 193 | 32 |
+- -+- -+- -+
| duplicate@gmail.com | 20 | 2 |
+- -+- -+- -+
| duplicate@gmail.com | 47 | 5 |
+- -+- -+- -+
Obviously duplicate@gmail.com has purchased from BrandID 20 twice and BrandID 47 5 times which is why they appear twice. Most customers have purchased from more than one brand.
From this information how can I construct a query to get the brand ID they have purchased from the most? I have tried the following but it just times out:
SELECT [table1].Email, [table1].Brand, [table1].CountOfBrand
FROM [Customer Brand Purchases] AS [table1]
GROUP BY [table1].Email, [table1].Brand, [table1].CountOfBrand
WHERE [table1].CountOfBrand=(
SELECT TOP 1 [table2].CountOfBrand
FROM [Customer Brand Purchases] AS [table2]
WHERE [table2].Email = [table1].Email
ORDER BY [table2].CountOfBrand DESC
);
Oh and I have to use Microsoft Access, unfortunately. Thanks.
I am reluctant to answer this as the thought of even assisting in the development of a database with a table name [Customer Brand Purchases] makes me feel a little bit sick.
My Access SQL is a little rusty but I am 98% certain this will work:
The only draw back is that if a particular customer has ordered 2 brands the same amount of times then it will return 2 rows. You would need additional subqueries with MAX statements in to resolve this.
EDIT/ADDENDUM:
If it is ABSOLUTELY imperative the query returns 1 result per email address then you need to allow for the scenario where a particular email address has purchased 2 brands and equal amount of times there is no way to establish which or these is favourite as they are joint favourite. If it were me I would deal with this at application level, and Concatenate favourite brands into one string. However, it can be done in SQL just be aware that one or more brands could be hidden using this: