2009-10-21 67 views
1
CREATE TABLE BlogPosts 
(
PostID INT PRIMARY KEY not null, 
PostTitle NVARCHAR , 
BlogID int, 
TotalComments int 
) 

可以使用任何聯接而不是相關子查詢簡化此查詢嗎?加入而不是相關的子查詢

SELECT TOP 5 * 
FROM BlogPosts as t0 
WHERE t0.PostID = (SELECT TOP 1 t1.PostID 
       FROM BlogPosts as t1 
       WHERE t0.BlogID = t1.BlogID 
       ORDER BY t1.TotalComments DESC) 

我需要5個帖子,最多TotalComments來自不同的博客。

UPD。 SQL Server中,但我寧願標準SQL

+0

什麼是RBDMS? SQL Server? – Asaph

+0

你聲明的sql沒有排序,所以前五個不能保證返回任何特定的五行......可能有更多的5行滿足Where子句......正如你寫的那樣,你可能會從同一個博客中獲取所有五個或混合。你想要哪一個? –

+0

不,我需要來自不同博客的頂級評論文章,不是來自同一個博客,否則它會更容易:) – rudnev

回答

1

如果我理解正確的,帖子ID是唯一的,所以這應該有助於

編輯:

OK試試這個,然後

DECLARE @BlogPosts TABLE 
( 
    PostID INT PRIMARY KEY not null, 
    PostTitle NVARCHAR , 
    BlogID int, 
    TotalComments int 
) 

INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 1, 'A', 1, 3 
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 2, 'B', 1, 4 
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 3, 'C', 2, 5 
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 4, 'D', 2, 6 
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 5, 'E', 2, 7 
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 6, 'F', 1, 8 
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 7, 'G', 3, 9 
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 8, 'H', 4, 10 
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 9, 'I', 5, 11 
INSERT INTO @BlogPosts (PostID,PostTitle,BlogID,TotalComments) SELECT 10, 'J', 6, 5 

SELECT TOP 5 * 
FROM @BlogPosts bp INNER JOIN 
     (
      SELECT BlogID, 
        MAX(TotalComments) MaxComments 
      FROM @BlogPosts 
      GROUP BY BlogID 
     ) maxCommentsPerBlog ON bp.BlogID = maxCommentsPerBlog.BlogID 
          AND bp.TotalComments = maxCommentsPerBlog.MaxComments 
ORDER BY bp.TotalComments DESC 

你可能有儘管多個最大的blog-totalComments組合。

+0

@astander:爲什麼「@BlogPosts」而不是「BlogPosts」?這不是臨時表。 – Asaph

+0

這是我在TSQL –

+0

中的測試表,你可能在這裏有相同的博客。我說不同的博客 – rudnev

1

這會給你每博客上一篇:

SELECT * FROM (
    SELECT *, Ranking = ROW_NUMBER() OVER (PARTITION BY BlogID ORDER BY TotalComments DESC) 
    FROM BlogPosts 
) a 
WHERE Ranking = 1 

或者:

SELECT b.* 
FROM (
    SELECT DISTINCT BlogID 
    FROM BlogPosts 
) a 
CROSS APPLY (
    SELECT TOP 1 b.* FROM BlogPosts b 
    WHERE a.BlogID = b.BlogID 
    ORDER BY b.TotalComments DESC 
) b 

這就是你想要的?

+0

隨着分區它是很好,謝謝,可能會比加入更好。 – rudnev

0

爲什麼你需要連接和子查詢? 爲什麼你不能寫

SELECT TOP 5 * 
FROM @BlogPosts bp order by TotalComments desc; 
+0

可能是因爲@rudnev需要來自不同博客的前5名「。您的查詢可能會返回僅有一個博客排名前5位。 –