选择语句以仅选择一个值

时间:2014-01-18 15:51:58

标签: sql sql-server-2008

我的项目有几个图像存储在表格中。

我想只检索第一张图片。

我该怎么办呢?

这是我的代码:

SELECT DISTINCT 
   Item.ItemID, Item.Name, Item.Description, Item.Quantity, 
   Item.Condition, Category.Name AS Expr1, Auction.EndDate, Auction.CurrencyValuePost, 
   Image.Image
FROM
   Item 
INNER JOIN
   Category ON Item.CategoryID = Category.CategoryID 
INNER JOIN
   Image ON Item.ItemID = Image.ItemID 
INNER JOIN
   Auction ON Item.ItemID = Auction.ItemID
WHERE        
   (Auction.Status = 'Valid')

2 个答案:

答案 0 :(得分:0)

SELECT
    Item.ItemID,
    Item.Name,
    Item.Description, 
    Item.Quantity,  
    Item.Condition,
    Category.Name AS Expr1,
    Auction.EndDate, 
    Auction.CurrencyValuePost, 
    Image.Image
FROM Item 
    INNER JOIN Category ON Item.CategoryID = Category.CategoryID 
    INNER JOIN Auction ON Item.ItemID = Auction.ItemID
    LEFT JOIN Image ON Item.ItemID = Image.ItemID 
WHERE        (Auction.Status = 'Valid')

答案 1 :(得分:0)

试试这个

Select * From
(
SELECT
    Item.ItemID,
    Item.Name,
    Item.Description, 
    Item.Quantity,  
    Item.Condition,
    Category.Name AS Expr1,
    Auction.EndDate, 
    Auction.CurrencyValuePost, 
    Image.Image,
    ROW_NUMBER() OVER(PARTITION BY  Item.ItemID ORDER BY  Item.ItemID ASC) AS RN
FROM Item 
    INNER JOIN Category ON Item.CategoryID = Category.CategoryID 
    INNER JOIN Auction ON Item.ItemID = Auction.ItemID
    LEFT JOIN Image ON Item.ItemID = Image.ItemID 
WHERE Auction.Status = 'Valid'
) AS T
Where RN=1