开发者

Transact SQL - How to perform additional operation on a result set

I have a simple query:

select id, count(*)开发者_开发知识库 n
from mytable
group by id

Is it possible to include also the sum(n) in the same query? So the result would look something like this:

id   n
---- -----------
1    12
2    1
3    14
4    1
5    2
6    6

Sum=36


You can use a common table expression to do this:

--
; WITH cte as (SELECT id
               ,count(*) n
               FROM mytable
               GROUP BY id)
SELECT id, n FROM cte
UNION ALL
SELECT 'Sum', SUM(n) from cte

You can also use ROLLUP: (this may not be exactly correct syntax)

SELECT id
      ,count(*) n
FROM mytable
GROUP BY id
WITH ROLLUP
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜