CountZero
CountZero

Reputation: 6389

SQL Help With Query - Group By and Aggreate Functions

I have a query I need some help with, have been checking out a fair few tutorials but nohting I found covers this issue.

I have three joined tables, Products,ProductImagesLookUp and Images.

A product can have any number of Images and the Order of the Images for a Product are stored in ProductImagesLookUp.

I need to return a list of products with their primary Image (the one with the lowest order value).

The list looks like this

Product
Images
LookUpId FileID Order    ProductTitle               Price   ProductId 
65       2     1    Amari Summer Party Dress    29.99      7
66       1     2    Amari Summer Party Dress    29.99      7
67       3     3    Amari Summer Party Dress    29.99      7
74       4     5    Beach Cover Up                  18.00     14
75       5     4    Beach Cover Up                  18.00     14
76       7     6    Beach Cover Up                  18.00     14
77       8     7    Beach Cover Up                  18.00     14
78       9     8    Beach Cover Up                  18.00     14
79       10    9    Amari Classic Party Dress   29.95     15
80       11    11   Amari Classic Party Dress   29.95     15
81       12    10   Amari Classic Party Dress   29.95     15

I want my query to pull back a list of distinct products which have the lowst Order value. I.e. it shoudl pull back the rows with the ProductImagesLookUpId of 65 (Product 7),74 ( Product 14) and 79 (Product 15).

Thanks in advance for your help. this one has really had me pulling my hair out!

Upvotes: 0

Views: 137

Answers (1)

Tomalak
Tomalak

Reputation: 338158

SELECT
  l.LookupId,
  i.FileId,
  l.[Order],  
  p.ProductTitle,
  p.Price,
  p.ProductId 
FROM
  Products p
  INNER JOIN ProductImagesLookUp l ON l.ProductId = p.ProductId
  INNER JOIN Images i ON i.FileId = l.FileId
WHERE
  i.[Order] = (
    SELECT MIN([Order]) 
    FROM ProductImagesLookUp 
    WHERE ProductId = p.ProductId
  )

There is no need to group by or aggregate anything since the sub-query ensures that there is not more than a single result row for any given ProductId — the one with the lowest Order.

Upvotes: 1

Related Questions