查找数据的百分比

时间:2016-03-27 02:51:23

标签: sql sql-server tsql percentage subtotal

这就是我的表格

Measure    PT Name
Expired    Mickey Mouse
Expired    Donald Duck
Alive      Big Bird
Alive      Baby Bird
Rehab      Daffy Duck
Xray       Goofy

我希望它看起来像这样:

Measure   Count  %
Expired   15     40%
Alive     5      13%
Rehab     7      18%
Xray      10     27%

我犯了一个错误,我想得到一个按Measure分组的计数,包括同一个SQL语句中的%all

Select DischargeDisp, Count(*) as TotalCnt
INTO #Measure
from #LOS
group by DischargeDisp

5 个答案:

答案 0 :(得分:0)

这就是你想要的吗?

Select Measure, Count(*), Count(*) * 100 / SUM ( COUNT (*) ) OVER()
from   #LOS
group by Measure

答案 1 :(得分:0)

select Measure
      ,SUM(m_count) m_count
      ,(sum(m_count)*100/(select sum(m_count) from your_table)) as Percentage
      from your_table group by Measure;

将列名count更改为m_count。因为它会造成混乱。

答案 2 :(得分:0)

SELECT Measure,
       SUM(Cnt) AS [Count],
       CAST(SUM(Cnt) * 100 / (SELECT SUM(Cnt) FROM #LOS) AS VARCHAR(10)) + '%' AS [%]
FROM #LOS
GROUP BY Measure

答案 3 :(得分:0)

您的问题不断变化,但这可能会满足您的需求:

Select Measure, Sum(1) as 'Count', LTrim(Str(Sum(1) * 100 / (Select Count(*) From Measure))) + '%' as [Percent]
  from Measure
  Group by Measure
order by Measure

答案 4 :(得分:0)

你可以用这个:

select distinct Measure, 
       count(*) over (partition by measure) as [Count],
       format(convert(float,count(*) over (partition by measure)) /count(*) over(),'p') as [%]
from los

测试是here