尝试获取另一个表的最后一行时重复的行

时间:2019-06-19 07:17:16

标签: sql sql-server stored-procedures

我正在尝试使用存储过程来获取每个月的最后(最新)博客文章链接,但似乎找不到解决问题的方法。

当前,我的下面代码像这样重复(最新博客文章的)“ LINK”列:

Results table

SELECT AVG(DATEPART(mm, b.blog_date)) AS MonthNum --CANNOT USE MONTHNUM IN ORDER BY UNLESS WRAPPED WITH AVG() [average], weird but works
 , CAST(DateName(month, DateAdd(month, Datepart(MONTH, b.blog_date), -1)) AS varchar(24)) AS MONTH
 , CAST(DATEPART(YEAR, b.blog_date) AS varchar(4)) AS YEAR
 , CAST(count(b.blog_content) AS varchar(24)) as ARTICLES
 , (SELECT TOP (1) b.blog_url
     FROM Management.Blog
     WHERE (website_owner_id = 2)
     GROUP BY blog_date
            , blog_url
     ORDER BY blog_date DESC
  ) AS LINK
 , CAST(DateName(month, DateAdd(month, Datepart(MONTH, b.blog_date), -1)) AS varchar(24)) + CAST(DATEPART(YEAR, b.blog_date) AS varchar(4)) AS ID
 , blog_date as DATE
FROM Management.Blog b 
WHERE b.website_owner_id = 2
GROUP BY CAST(DateName(month, DateAdd(month, Datepart(MONTH, b.blog_date), -1)) AS varchar(24))
  , CAST(DATEPART(YEAR, b.blog_date) AS varchar(4))
  , b.blog_url
  , blog_date
  , CAST(DateName(month, DateAdd(month, Datepart(MONTH, b.blog_date), -1)) AS varchar(24)) + CAST(DATEPART(YEAR, b.blog_date) AS varchar(4))
 ORDER BY DATE DESC

我知道代码很容易阅读(很可能也要在SQL服务器上执行),但是我处于对SQL服务器不熟悉的位置(来自MySQL,实际上我只需要使用它)一个基本的选择查询),我乐于接受任何有关更改查询和/或表设计的建议。

从本质上讲,ID列不应有重复项(只是真正添加了ID列以帮助删除重复项,如果需要可以将其省略)。

2 个答案:

答案 0 :(得分:0)

没有示例数据,我无法测试这是否可行

FROM Management.Blog b之后 添加

INNER JOIN(
    SELECT   MonthNum   = DATEPART(MONTH, BL.blog_date))
            ,blog_date
            ,RN         = ROW_NUMBER()OVER(ORDER BY BL.blog_date DESC)
            ,BL.blog_url
    FROM    Management.Blog BL
) X ON  B.blog_date = X.blog_date
    AND X.RN = 1

替换

(SELECT TOP (1) b.blog_url
     FROM Management.Blog
     WHERE (website_owner_id = 2)
     GROUP BY blog_date
            , blog_url
     ORDER BY blog_date DESC
  ) AS LINK

使用

X.blog_url AS [LINK]

GROUP BY

中进行更改
, b.blog_url

使用

, x.blog_url

答案 1 :(得分:0)

我无法正常运行的查询通常无法很好地传达某人的需求。根据您的解释:

  

我正在尝试获取每个月的最后(最新)博客文章链接

我期望这样的事情:

SELECT b.*
FROM (SELECT b.*,
             ROW_NUMBER() OVER (PARTITION BY YEAR(b.blog_date), MONTH(b.blog_date), b.blog_url, b.website_owner_id
                                ORDER BY blog_date DESC
                               ) as seqnum
      FROM Management.Blog b 
     ) b
WHERE b.website_owner_id = 2 AND
      seqnum = 1;