3

I have two tables Product and images. The values in the two tables are given below

SELECT * FROM ProductTable

Structure is (Productid, Categoryid, ProductName)

1   1   Product1
2   1   Product2
3   2   Product2
4   2   Product3
5   2   Product4

SELECT * FROM ImageTable

Structure is (ImageID, ProductID, ImageName)

1   1   Image1
2   1   Image2
3   2   Image3
4   2   Image4
5   4   Image5
6   5   Image6

My query is :

SELECT ImageTable.ProductID, ImageName 
FROM ImageTable 
LEFT JOIN ProductTable ON ImageTable.ProductID=ProductTable.ProductID 
GROUP BY ImageTable.ProductID, ImageName

The result is :

1   Image1
1   Image2
2   Image3
2   Image4
4   Image5
5   Image6

But I want the result as (i.e. the First Imagename of the Productid from the imagetable)

1       Image1
2       IMage3
4       Image5
5       Image6
1
  • Is "first" defined as the row with the lowest ImageId value? Because tables, by definition, do not have an order. Commented Jul 19, 2013 at 6:39

3 Answers 3

2
SELECT ImageTable.ProductID, MIN(ImageName)
FROM ImageTable 
LEFT JOIN ProductTable ON ImageTable.ProductID=ProductTable.ProductID 
GROUP by ImageTable.ProductID
Sign up to request clarification or add additional context in comments.

1 Comment

it sql server you must put column that are in select list either in group by or aggregate function t otherwise it give u error
2

Really LEFT JOIN with ProductTable is unnecessary. So try this one -

SELECT ProductID, ImageName
FROM (
     SELECT 
            i.ProductID
          , i.ImageName
          , rn = ROW_NUMBER() OVER (PARTITION BY i.ProductID ORDER BY i.ImageName)
     FROM dbo.ImageTable i
) t
WHERE t.rn = 1

Or try this -

SELECT 
       i.ProductID
     , ImageName = MIN(i.ImageName)
FROM dbo.ImageTable i
GROUP BY i.ProductID

Output -

ProductID   ImageName
----------- ---------
1           Image1
2           Image3
4           Image5
5           Image6

3 Comments

I just used MIN() without understanding his actual query. +1 for taking time to answer and proving simple queries.
Thanks. @hims056, can you undelete your answer? I can't up-vote it.
@hims056, but you can always improve it.
2
SELECT ProductID, MIN(ImageName) 
     FROM 
       ImageTable 
GROUP by ProductID

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.