-1

我有一个包含列的表:

AnswerID、OwnerUserID、CreationDate

如何使用 OwnerUserID 在为该 AnswerID 列出的 CreationDate 之前发布的答案总数填充标题为 (AnswersPosted) 的第四列?

编辑:

下面是表格应该是什么样子的示例。(抱歉,我刚加入后无法发布图片……)我有兴趣让最后一列显示所有正确的数字。谢谢!

在此处输入图像描述

4

1 回答 1

2

Use this solution:

SELECT a.AnswerID,
       a.OwnerUserID,
       a.CreationDate,
       b.cnt AS AnswersPosted
FROM   tbl a
JOIN   (
       SELECT    a.OwnerUserID,
                 a.CreationDate,
                 COUNT(b.OwnerUserID) AS cnt
       FROM      tbl a
       LEFT JOIN tbl b ON a.OwnerUserID  = b.OwnerUserID
                      AND b.CreationDate < a.CreationDate
       GROUP BY  a.OwnerUserID,
                 a.CreationDate
       ) b ON a.OwnerUserID  = b.OwnerUserID
          AND a.CreationDate = b.CreationDate

SQLFiddle Demo

于 2012-08-16T21:29:58.847 回答