简体   繁体   中英

Pivoting Row Counts into Ratios Column? (in MS-SQL)

I've got the following query:

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

Which gives me something like:

IsCancelled      Count
0                7851
1                11235

Say I wanted to add another column with the percentages relative to each row, I should get the following:

IsCancelled      Count     Ratio
0                7851      0.41135
1                11235     0.58865

This is called a Pivot correct? How would I accomplish this calculation? What do I add to my query above to make this happen? Thanks ;)

IMPLEMENTATION

I ended up modifying diaho's answer a bit as follows:

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

You'll have to use a subquery. The query below should work in sqlserver and mysql, but I'm not sure it will work in ever 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

An alternate way...

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

The key here is to do this in one query or transaction or your count could change from one query to the next.

try the following

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

If you are using SQL Server 2005 or later:

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

References:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM