SELECT [ReferredDoctor_ID] , [count] , SUM([count]) [returns]
FROM (SELECT O.[ReferredDoctor_ID], COUNT(1) [count]
FROM [dbo].[Order] O WITH (NOLOCK)
WHERE O.agency_id = @agency_id AND O.Trash = 0 AND
O.DateCreatedByServer BETWEEN @datefrom AND @dateto
GROUP BY O.[ReferredDoctor_ID]
) dd
GROUP BY [ReferredDoctor_ID] , [count]
ORDER BY [count] DESC
答案 0 :(得分:2)
如果你想要计数和总和,你可以使用窗口函数:
SELECT O.[ReferredDoctor_ID], COUNT(*) as cnt,
SUM(COUNT(*)) OVER () as total_cnt
FROM [dbo].[Order] O
WHERE O.agency_id = @agency_id AND O.Trash = 0 AND
O.DateCreatedByServer BETWEEN @datefrom AND @dateto
GROUP BY O.ReferredDoctor_ID;