SQL Count / sum in order子句

时间:2013-11-23 04:31:56

标签: sql sql-server tsql

我正在为我正在处理的工具制作一个“排行榜”,我需要将一些数字拉到一起并获得多行记录的数量。

您将在此存储过程中看到的是我尝试按2列的总和对记录进行排序。

有关如何完成此任务的任何提示?

AS
BEGIN
SET NOCOUNT ON;
        BEGIN
            SELECT DISTINCT(whoAdded),
                    count(tag) as totalTags,
                    count(DISTINCT data) as totalSubmissions
            FROM   Tags_Accounts
            GROUP BY whoAdded
            ORDER BY SUM(totalTags + totalSubmissions) DESC
            FOR    XML PATH ('leaderboard'), TYPE, ELEMENTS, ROOT ('root');
        END 
END

3 个答案:

答案 0 :(得分:0)

您可以通过将其放在派生表中来实现此目的:

SELECT *
FROM (
    SELECT DISTINCT(whoAdded) AS whoAdded,
        count(tag) as totalTags,
        count(DISTINCT data) as totalSubmissions
    FROM   Tags_Accounts
    GROUP BY whoAdded
    ) a
ORDER BY totalTags + totalSubmissions DESC
FOR    XML PATH ('leaderboard'), TYPE, ELEMENTS, ROOT ('root')

或者,你可以通过聚合来订购,但我认为上面的内容更清晰/更少:

SELECT DISTINCT(whoAdded) as whoAdded,
    count(tag) as totalTags,
    count(DISTINCT data) as totalSubmissions
FROM   Tags_Accounts
GROUP BY whoAdded
ORDER BY SUM(count(tag) + count(DISTINCT data)) DESC
FOR    XML PATH ('leaderboard'), TYPE, ELEMENTS, ROOT ('root')

答案 1 :(得分:0)

SET NOCOUNT ON;
        BEGIN
            ;WITH CTE AS(
            SELECT DISTINCT(whoAdded),
                    count(tag) as totalTags,
                    count(DISTINCT data) as totalSubmissions
            FROM   Tags_Accounts
            GROUP BY whoAdded)
            SELECT * FROM CTE
            ORDER BY SUM(totalTags + totalSubmissions) DESC
            FOR    XML PATH ('leaderboard'), TYPE, ELEMENTS, ROOT ('root');
        END 
END

答案 2 :(得分:0)

不要使用SUM(),只需使用+添加值,只使用表达式而不是列别名:

ORDER BY count(*) + count(DISTINCT data) DESC