如何在使用group by时获得计数总和

时间:2017-03-27 00:41:09

标签: sql sql-server

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

1 个答案:

答案 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;