1

我目前正在尝试将另一列 (PictureCount) 添加到我的结果集中,该列从另一个表返回位于每个唯一图库中的图像计数。(GalleryID 将它们链接在一起。)每个 GalleryID 可以有 3 到 20 个与之关联的 MediaID。

我不是 SQL 专家,所以我可以使用一些帮助。我什至不确定是否可以返回我正在寻找的计数。

谢谢!

这是 2 个表的简单视图。

帮助您的 SQL Fiddle:http ://sqlfiddle.com/#!3/72935/16

这是我当前的查询,它返回我需要的所有内容,除了我不知道该怎么做的 Count 列。

WITH CTE AS (
    SELECT a.GalleryTitle, a.GalleryDate, b.*,  
    ROW_NUMBER() OVER (PARTITION BY  a.GalleryID, a.GalleryTitle, a.GalleryDate 
    ORDER BY b.MediaThumb DESC) AS Rn
    FROM Media b
    INNER JOIN Galleries A
    ON a.GalleryID = b.GalleryID
    WHERE b.IsPlug = 0 AND b.IsHidden = 0
),

CTE2 AS
(
    SELECT a.GalleryTitle, a.GalleryDate, b.*,  
    1 Rn
    FROM Media b
    LEFT OUTER JOIN Galleries A
    ON a.GalleryID = b.GalleryID
)

SELECT *, NewID = NEWID() FROM CTE WHERE rn = 1 and MediaTypeID = 4

UNION ALL

SELECT *, NewID = NEWID() FROM CTE2 WHERE rn = 1 and MediaTypeID = 4 and GalleryID is NULL
ORDER BY GalleryDate DESC, GalleryID DESC
4

1 回答 1

1

这应该有效:

WITH cte As
(
   SELECT
      a.GalleryID As GalleryID_A,
      a.GalleryTitle,
      a.GalleryDate,
      b.*,

      -- You only need to partition by GalleryID:
      ROW_NUMBER() OVER (PARTITION BY b.GalleryID ORDER BY b.MediaThumb DESC) As Rn,

      -- This will return the number of media records per gallery:
      COUNT(1) OVER (PARTITION BY b.GalleryID) As Rc
   FROM
      Media As b
      -- The LEFT JOIN will include media with no gallery,
      -- so your second CTE is not needed:
      LEFT JOIN Gallery As A
      ON b.GalleryID = A.GalleryID
   WHERE
      -- This filter needs to be within the CTE,
      -- otherwise you'll exclude galleries where the last
      -- media is not type 4:
      b.MediaTypeID = 4
)
SELECT
   *
FROM
   cte
WHERE
   rn = 1
ORDER BY 
   GalleryDate DESC, 
   GalleryID DESC
;
于 2012-11-27T19:07:19.507 回答