SQL Query从一个表中取出前1行,并将其作为列字段放在另一个表中

时间:2014-03-20 21:44:47

标签: sql-server

我正在尝试从产品表中获取与类别ID匹配的第一行,并将该值放入类别表元描述字段中,此时它将最后一条记录放入字段中,但我需要第一条记录这是最好的卖家。

我试图使用的代码如下,我已经迟到了,我很累,如果一个神奇的仙女可以来帮助我解决这个问题,我将向你发送100个Karma积分。

 UPDATE Category 
SET
    MetaTitle  = Name + ' Audio Books',
    MetaKeywords = Name + ' ,audio books, download, free, audio book, online, audio book, audiobooks, audiobook, mp3 books, cd, free trial, spoken, spoken word, talking, talking books',
    MetaDescription = 'Our best sellers in audio books for ' + Name + ' which includes ' + pname

    FROM
    (
    SELECT TOP 1
        p.Name as pname,
        pcm.CategoryId as pCat,
        p.CreatedOnUtc 
    FROM 
        Product p
    INNER JOIN 
        Product_Category_Mapping pcm
    ON 
        p.Id = pcm.ProductId
    ORDER BY 
        CreatedOnUtc DESC
    ) newproduct 
WHERE
    Category.Id = newproduct.pCat 
and Category.Id >=22
and ParentCategoryId <> 0

ps:在desc上创建将显示我想要的记录。

1 个答案:

答案 0 :(得分:0)

FROM()内的查询只会获得单个最新产品(在所有类别中)。因此,它只会更新该产品所属的任何类别。

您需要获得每个类别的顶级产品。试试这个:

UPDATE Category
SET
    MetaTitle = Name + ' Audio Books',
    MetaKeywords = Name + ' ,audio books, download, free, audio book, online, audio book, audiobooks, audiobook, mp3 books, cd, free trial, spoken, spoken word, talking, talking books',
    MetaDescription = 'Our best sellers in audio books for ' + Name + ' which includes ' + pname
FROM
(
     SELECT
        p.Name AS pname,
        pcm.CategoryId AS pCat,
        p.CreatedOnUtc,
        ROW_NUMBER() OVER (
            PARTITION BY pcm.CategoryId 
            ORDER BY CreatedOnUtc DESC
        ) AS RowNumber
     FROM Product p
     INNER JOIN Product_Category_Mapping pcm
        ON p.Id = pcm.ProductId
) newproduct
WHERE
    newproduct.RowNumber = 1
    AND Category.Id = newproduct.pCat 
    AND Category.Id >=22
    AND ParentCategoryId <> 0