SQL Server计算sql pivot值的百分比

时间:2012-02-10 13:02:57

标签: sql sql-server pivot

我目前有一个SQL Server数据透视表,其中包含每月和每input sales

的值

我想计算input_sales = 'OK'的百分比。

我该怎么做?

SIGNED  INPUT_SALES DEALER     D2D  CALLCENTER  INTERNET</tr>
2012-01 NOK          158       1231     309       214
2012-01 OK           417       4634    4047      1491
2011-12 NOK          301       1637     404       245
2011-12 OK           615       4195    4334      1985

我的代码:

SELECT SIGNED_DATE, 
    INPUT_SALES, 
    [DEALER] AS DEALER, 
    [D2D] AS D2D, 
    [CALLCENTER] AS CALLCENTER, 
    [INTERNET] AS INTERNET
FROM
(
    SELECT ENTITLEMENT_ID, SALES_CHANNEL, SIGNED_DATE, INPUT_SALES
    FROM #TEMP
) T
PIVOT
(
    COUNT (ENTITLEMENT_ID)
    FOR SALES_CHANNEL IN
        ([DEALER], [D2D], [CALLCENTER], [INTERNET])
) AS PVT
ORDER BY PVT.SIGNED_DATE DESC

2 个答案:

答案 0 :(得分:0)

应该是

with total as (
select COUNT(INPUT_SALES)as id from t),
counted as (select count(INPUT_SALES) as id from t where t.INPUT_SALES='OK')
select 100.0*counted.INPUT_SALES/total.INPUT_SALES from total,counted
group by total.INPUT_SALES,counted.INPUT_SALES

希望有所帮助

答案 1 :(得分:0)

试试这个:

select INPUT_SALES , cast(count(*) as numeric(5,2)) * 100 /(select count(*) from TABLE_INPUT_SALES )
from TABLE_INPUT_SALES 
where INPUT_SALES ='OK'
group by INPUT_SALES