计算SQL Server中总计的百分比

时间:2018-08-15 16:11:06

标签: sql-server

如何计算总百分比,就像我们在excel中使用的那样,将计数显示为%。

请参考所附的屏幕截图,我需要使用%明智的显示方式,而不是数字。

enter image description here

下面是我的SQL查询:

SELECT
[Region]=ISNULL(zone, 'Grand Total'),
[chennai]=SUM([chennai]),
[Kandivali]=SUM([Kandivali]),
[kolhapur]=SUM([kolhapur])
from
(select zone,[Ret#Location]
from [Test].[dbo].[dailyAssure_1]
) src
pivot
(count([Ret#Location])
for [Ret#Location] in ([chennai], [Kandivali], [kolhapur])
) piv
Group by ROLLUP(zone);

1 个答案:

答案 0 :(得分:1)

这有点骇人听闻,但与此类似的东西可能会起作用...

with 
    data as (
        -- this is your query
        SELECT  [Region]=zone,
                [chennai]=SUM([chennai]),
                [Kandivali]=SUM([Kandivali]),
                [kolhapur]=SUM([kolhapur])
        from    (select zone, [Ret#Location] from [Test].[dbo].[dailyAssure_1]) src
        pivot
        (count([Ret#Location]) for [Ret#Location] in ([chennai], [Kandivali], [kolhapur]) ) piv
        Group by ROLLUP(zone)
    ) ,
    totals as (
        -- one row with totals for chennai, etc...
        select  zone='Grand Total', 
                chennai=sum(chennai), 
                kandivali=sum(kandivali), 
                kolhapur=sum(kolhapur)
        from    data
    )
select  d.zone ,
        d.chennai / t.chennai as chennai ,
        d.kandivali/ t.kandivali as kandvali ,
        d.kolhapur / t.kolhapur as kolhapur
from    data d
cross join totals t
;

它不包括总行(无论如何总为1),您可能需要转换%计算中使用的值(或%值本身)以获得所需的输出格式。