3

我有两张桌子Productimages. 下面给出了两个表中的值

SELECT * FROM ProductTable

结构为(Productid、Categoryid、ProductName)

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

SELECT * FROM ImageTable

结构为 (ImageID, ProductID, ImageName)

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

我的查询是:

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

结果是:

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

但我希望结果为(即图像表中 Productid 的第一个图像名)

1       Image1
2       IMage3
4       Image5
5       Image6
4

3 回答 3

3

LEFT JOINProductTable是不必要的。所以试试这个 -

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

或者试试这个 -

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

输出 -

ProductID   ImageName
----------- ---------
1           Image1
2           Image3
4           Image5
5           Image6
于 2013-07-19T06:20:53.513 回答
2
SELECT ImageTable.ProductID, MIN(ImageName)
FROM ImageTable 
LEFT JOIN ProductTable ON ImageTable.ProductID=ProductTable.ProductID 
GROUP by ImageTable.ProductID
于 2013-07-19T06:17:17.740 回答
2
SELECT ProductID, MIN(ImageName) 
     FROM 
       ImageTable 
GROUP by ProductID
于 2013-07-19T07:08:15.940 回答