SQL Server:按组和总计COUNT

时间:2016-07-20 22:25:21

标签: sql sql-server count

我的group by子句的sql语句如下:

number count
1       10
2        5
3        6

输出:

 number count
    1       10
    2        5
    3        6
   total    21

我应该如何修改我的查询以获得表中的总数,如下所示:

{ 
 "to": "<registration token>",
 "priority": "high",
 "notification": {
    "title": "Your Title",
    "text": "Your Text"
  }
 "data": {
     "customId": "<my custom id>",
     "badge": 1,
     "sound": "cheering.caf",
    "alert": "New data is available"
  }
}

3 个答案:

答案 0 :(得分:2)

由于您可能正在使用SQL Server,因此可以使用with rollup

select coalesce([number], 'total') as [number]
     , count(*) as [count]
from [mytable]
group by [number]
with rollup

答案 1 :(得分:0)

根据您的特定SQL方言,您可以尝试类似

的内容
select number , count (*) as 'count' from mytable
group by number

union

select 'Total' as 'number', count (*) as 'count' from mytable

答案 2 :(得分:0)

当与最后一行中的“total”文本结合时,您需要将数字列强制转换为char。以下语法TO_CHAR适用于Oracle:

select TO_CHAR(num) , count (*) as "count" 
from mytable
group by num
union all
select 'total' , sum(count (*)) as "count" 
from mytable
group by num

或mysql:

select CAST(num as CHAR(10)) , count (*) as "count" 
from mytable
group by num
union all
select 'total' , sum(count (*)) as "count" 
from mytable
group by num
相关问题