我想获得行的总结果。例如,如果数据库有10条记录,那么输出应为10。
我的查询是
select COUNT(*) AS NumberRow from
(SELECT TOP 30 PERCENT [EmpName], sum(Scoring) as GrandTotal
FROM [masterView] GROUP BY [EmpName]
ORDER BY GrandTotal DESC,EmpName ASC)
但是有一个错误: -
错误是:
消息102,级别15,状态1,行4'''附近的语法不正确。
答案 0 :(得分:1)
您应该使用子查询别名:
SELECT COUNT(*) AS NumberRow
FROM ( SELECT TOP 30 PERCENT
[EmpName] ,
SUM(Scoring) AS GrandTotal
FROM [masterView]
GROUP BY [EmpName]
ORDER BY GrandTotal DESC ,
EmpName ASC
) t
您可以使用窗口函数将数据与聚合混合:
SELECT *, COUNT(*) OVER() AS NumberRow
FROM ( SELECT TOP 30 PERCENT
[EmpName] ,
SUM(Scoring) AS GrandTotal
FROM [masterView]
GROUP BY [EmpName]
ORDER BY GrandTotal DESC ,
EmpName ASC
) t
答案 1 :(得分:0)
别名的东西肯定会像Giorgi上面提到的那样起作用。但是,如果您的数据库有10条Employees记录,那么当您选择TOP 30 PERCENT时,您的查询将只返回3条记录而不是10条记录。以下查询应返回10条记录。
select COUNT(*) AS NumberRow from
( SELECT [EmpName], sum(Scoring) as GrandTotal
FROM [masterView] GROUP BY [EmpName]
ORDER BY GrandTotal DESC,EmpName ASC
)temp