将行计数转入比率列? (在MS-SQL中)

时间:2012-03-07 20:32:37

标签: sql sql-server pivot

我有以下查询:

select a.IsCancelled, count(*) from tblTask a
    inner join tblTicket t on a.TicketID = t.TID
    group by a.IsCancelled

这给了我类似的东西:

IsCancelled      Count
0                7851
1                11235

假设我想添加另一列,其中百分比相对于每一行,我应该得到以下内容:

IsCancelled      Count     Ratio
0                7851      0.41135
1                11235     0.58865

这被称为Pivot正确吗?我该如何完成这个计算?为了实现这一目标,我在上面的查询中添加了什么?谢谢;)

实施

我最后修改了diaho的答案如下:

declare @tbl table (IsCancelled bit, [Count] int)
insert into @tbl
    select a.IsCancelled, count(*) [Count] from tblTask a
        inner join tblTicket t on a.TicketID = t.TID
        group by a.IsCancelled
select IsCancelled, [Count], round(cast([Count] as float)/(select sum([Count])
    from @tbl),5) [Ratio] from @tbl

3 个答案:

答案 0 :(得分:2)

您必须使用子查询。下面的查询应该在sqlserver和mysql中工作,但我不确定它是否会在rdbms中工作。

select a.IsCancelled, count(*), count(*)/(select count(*) from tblTask) 
from tblTask a
inner join tblTicket t on a.TicketID = t.TID
group by a.IsCancelled

另一种方式......

select a.IsCancelled, count(*), count(*)/totalcount
from tblTask a,
tblTicket t,
(select IsCancelled, count(*) as totalcount from tblTask) as tablecount, 
where a.TicketID = t.TID
group by a.IsCancelled

这里的关键是在一个查询或事务中执行此操作,否则您的计数可能会从一个查询更改为下一个查询。

答案 1 :(得分:2)

尝试以下

DECLARE @Total INT

SELECT @Total = select count(1) from tblTask

select a.IsCancelled, count(1), count(1)/@Total
from tblTask a
inner join tblTicket t on a.TicketID = t.TID
group by a.IsCancelled

答案 2 :(得分:1)

如果您使用的是SQL Server 2005或更高版本:

SELECT
  a.IsCancelled,
  Count = COUNT(*),
  Ratio = COUNT(*) * 1.0 / SUM(COUNT(*)) OVER ()
FROM tblTask a
  INNER JOIN tblTicket t ON a.TicketID = t.TID
GROUP BY a.IsCancelled

参考文献: