尝试获取占总数的百分比

时间:2019-05-13 18:17:40

标签: sql-server group-by percentage

除了每个分组的计数之外,我正在尝试获取总记录的百分比。

例如,我在下面有一个查询,在这里我可以得到符合“接触”条件和没有接触条件的记录总数。

然后,我想获取这些计数的整体百分比(如果“触摸”了40/50条记录,则应该显示80%)

不适用

SELECT COUNT(Contact) AS [COUNT],
       (CASE WHEN number>=1 THEN 'Touched' ELSE 'Not Touched' END) AS TOUCHED
FROM Events
GROUP BY (CASE WHEN number>=1 THEN 'Touched' ELSE 'Not Touched' END)

Count    TOUCHED
604      Not Touched
213      Touched

应该再增加一列,其中“未触摸”的百分比显示为73.92%,“已触摸”的百分比显示为26.07%

4 个答案:

答案 0 :(得分:1)

COUNT() * 100 / SUM()将返回百分比:

SELECT COUNT(Contact) AS COUNT,
    (CASE WHEN number >= 1 THEN 'Touched' ELSE 'Not Touched' END) AS TOUCHED,
    (COUNT(Contact) * 100 / SUM(Contact)) AS PERCENT
FROM Events
GROUP BY (CASE WHEN number >= 1 THEN 'Touched' ELSE 'Not Touched' END)

答案 1 :(得分:0)

这应该给您带来的帮助:

SELECT COUNT(Contact) AS [COUNT],
       (COUNT(Contact) * 1.0) / COUNT(Contact) OVER () AS Perc,
       CASE WHEN number>=1 THEN 'Touched' ELSE 'Not Touched' END AS TOUCHED
FROM Events
GROUP BY CASE WHEN number>=1 THEN 'Touched' ELSE 'Not Touched' END;

您可以使用“窗口”获取组外的总数,并以此来计数。

答案 2 :(得分:0)

只需用以下内容包装它:

Select ([Touched]/[Not touched])*100
From (
Your code

)

这也可以通过将其插入到临时表中并对列进行相同的操作来实现。

您可能必须将[touched]转换/转换为小数。

答案 3 :(得分:0)

此版本将原始查询中的标签替换为列名。如果您需要内联标签,则更改应该很简单:

SELECT 
    Touched,
    Cast(Touched/Cast(Total as decimal(9,2)) * 100.0 as Decimal(5,2)) as TouchedPct,
    Total - Touched as [Not Touched],
    Cast((Total - Touched)/Cast(Total as decimal(9,0)) * 100.0 as Decimal(5,2)) as NotTouchedPct
FROM (
    SELECT 
        SUM(CASE WHEN number >= 1 then 1 else 0 END) as Touched,
        Count(*) as Total
    FROM Events
    ) src

请注意,如果number永远不能为负,则可以将Touched计算更改为

SUM(SIGN(number)) as Touched,