SQL QUARE for SQLSERVER 2008

时间:2013-07-19 06:12:10

标签: sql sql-server sql-server-2008

我有两张表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

3 个答案:

答案 0 :(得分:3)

LEFT JOIN真的ProductTable是不必要的。所以试试这个 -

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

答案 1 :(得分:2)

SELECT ImageTable.ProductID, MIN(ImageName)
FROM ImageTable 
LEFT JOIN ProductTable ON ImageTable.ProductID=ProductTable.ProductID 
GROUP by ImageTable.ProductID

答案 2 :(得分:2)

SELECT ProductID, MIN(ImageName) 
     FROM 
       ImageTable 
GROUP by ProductID