SQL Server 2008中的平均计算

时间:2016-03-24 08:55:09

标签: sql sql-server tsql

我正在尝试计算值列的填充率的总体平均值, 但是只有当它的描述不为null时,如果description和value为null,那么它应该从平均计算中排除。

DECLARE @MASTER TABLE
(
    PRODUCT    VARCHAR (50),
    Desc1      VARCHAR (50),
    Desc1Value VARCHAR (50),    
    Desc2      VARCHAR (50),
    Desc2Value VARCHAR (50), 
    Desc3      VARCHAR (50),
    Desc3Value VARCHAR (50),
    Desc4      VARCHAR (50),
    Desc4Value VARCHAR (50),
    Desc5      VARCHAR (50),
    Desc5Value VARCHAR (50),
    Desc6      VARCHAR (50),
    Desc6Value VARCHAR (50)
)

INSERT @MASTER
    SELECT 
        'AMPLIFIER', 'Color', 'Black', 'Material',  
        'Blended TPO', 'Edge Type', 'Raised', 
        'Surface Type', 'Non-Skid', 'Coverage', NULL,   
        NULL, NULL 

    UNION ALL

    SELECT 
        'AMPLIFIER', 'Color', 'Black', 'Material', 'Blended TPO',   
        'Edge Type', 'Raised', 'Surface Type', 'Non-Skid',  
        'Coverage', NULL, NULL, NULL 

    UNION ALL

    SELECT 
        'RECTIFIER', 'Style', 'Film Kit', 'Color', 'Clear', 
        'Material', 'Urethane', 'Quantity', NULL, NULL, NULL,   
        NULL, NULL 

    UNION ALL

    SELECT 
        'RECTIFIER', 'Style', 'Film Kit', 'Color', 'Clear', 
        'Material', 'Urethane', 'Quantity', NULL, NULL, NULL,   
        NULL, NULL 

    UNION ALL

    SELECT 
        'Diode', 'Rating', '6 Ampere', 'Quantity', 'Pack Of 12',    
        NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL

预期产出:

Overall_fillrate:- 68.33%

愿任何人请帮助我,我尝试多种方式但无法实现它。

谢谢,

1 个答案:

答案 0 :(得分:1)

像这样?

select  (COUNT(CASE WHEN Desc1 is not null then Desc1Value end)
    + COUNT(CASE WHEN Desc2 is not null then Desc2Value end)
    + COUNT(CASE WHEN Desc3 is not null then Desc3Value end)
    + COUNT(CASE WHEN Desc4 is not null then Desc4Value end)
    + COUNT(CASE WHEN Desc5 is not null then Desc5Value end)
    + COUNT(CASE WHEN Desc6 is not null then Desc6Value end))
    * 100.0
    / ( 6 * COUNT(*))
from    @MASTER