Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>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.</p> <p>My Access SQL is a little rusty but I am 98% certain this will work:</p> <pre><code>SELECT CBP.Email, CBP.Brand AS [Favourite Brand ID] FROM [Customer Brand Purchases] AS CBP INNER JOIN ( SELECT [Email], MAX(CountofBrand) AS [MaxCountofBrand] FROM [Customer Brand Purchases] GROUP BY [Email] ) AS [MaxCBP] ON CBP.Email = MaxCBP.Email AND CBP.CountOfBrand = MaxCBP.MaxCountOfBrand </code></pre> <p>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.</p> <p>EDIT/ADDENDUM:</p> <p>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:</p> <pre><code>SELECT CBP.Email, CBP.Brand AS [Favourite Brand ID] FROM [Customer Brand Purchases] AS CBP INNER JOIN ( SELECT CBP.Email, MAX(CBP.Brand) AS MaxBrand FROM [Customer Brand Purchases] AS CBP INNER JOIN ( SELECT [Email], MAX(CountofBrand) AS MaxCountofBrand FROM [Customer Brand Purchases] GROUP BY [Email] ) AS MaxCBP ON CBP.Email = MaxCBP.Email AND CBP.CountOfBrand = MaxCBP.MaxCountOfBrand GROUP BY Email ) AS MaxCBP ON CBP.Email = MaxCBP.Email AND CBP.Brand = MaxCBP.Brand </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload