sql server 2008

时间:2016-03-22 09:21:30

标签: sql sql-server

sql server 2008

我有一个表格,我在计算所有列的值列中可用数据的百分比。

现在我正在尝试计算值列

中可用数据的平均百分比

但挑战在于计算超过所有平均值 我需要排除这些类型的列 例如

如果DENTAL为NULL且DENTAL_VALUE为NULL,我在计算平均值时不应考虑。

但如果DENTAL为NOT NULL且DENTAL_VALUE为NULL,则将包括在计算中。

以下脚本为我提供了每列的平均值

任何人都可以帮助我如何计算上述情景的总体平均值

在这种情况下,在计算整体平均值时,我必须排除牙科和牙科值,但不排除肾脏。

DECLARE @PHARMA TABLE
(
MRN VARCHAR (30),
department VARCHAR (30),
optical VARCHAR (30),
optical_value VARCHAR (30), 
dermo VARCHAR (30),
dermo_value VARCHAR (30),
Neuro VARCHAR (30),
Neuro_value VARCHAR (30),
DENTAL VARCHAR (30),
DENTAL_VALUE VARCHAR (30)
   Nephro VARCHAR (30),
    Nephro_VALUE VARCHAR (30)
)

Insert @PHARMA

SELECT 'BSE23098', 'Clinic', 'Willmar','10', 'Betamethasone' ,'20', 'neurobion', NULL,NULL,NULL,'TYPE-A',NULL UNION ALL

SELECT 'ZSE23098', 'Clinic', 'AUROBRIME','10', 'adapalene' ,'20', 'Blong', NULL,NULL,NULL,'TYPE-B',NULL UNION ALL
SELECT 'ZSE23098', 'Clinic', 'VOZOLE', NULL, 'SURFRAZ', '30' ,'Evion', '63' ,NULL,NULL,'TYPE-C',NULL

查询:

SELECT 
    CAST(optical_not_NULL * 100.0 / NULLIF((optical_NULL + optical_not_NULL), 0) AS decimal(5, 2)) AS optical_fill_rate,
    CAST(dermo_not_NULL * 100.0 / NULLIF((dermo_NULL + dermo_not_NULL), 0) AS decimal(5, 2)) AS dermo_fill_rate,
    CAST(dental_not_NULL * 100.0 / NULLIF((dental_NULL + dental_not_NULL), 0) AS decimal(5, 2)) AS dental_fill_rate,
    CAST(neuro_not_NULL * 100.0 / NULLIF((neuro_NULL + neuro_not_NULL), 0) AS decimal(5, 2)) AS neuro_fill_rate
FROM (
    SELECT
        SUM(CASE WHEN optical_value IS NULL THEN 1 ELSE 0 END) AS optical_NULL,
        SUM(CASE WHEN optical_value IS NULL THEN 0 ELSE 1 END) AS optical_not_NULL,
        SUM(CASE WHEN dermo_value IS NULL THEN 1 ELSE 0 END) AS dermo_NULL,
        SUM(CASE WHEN dermo_value IS NULL THEN 0 ELSE 1 END) AS dermo_not_NULL,
        SUM(CASE WHEN neuro_value IS NULL THEN 1 ELSE 0 END) AS neuro_NULL,
        SUM(CASE WHEN neuro_value IS NULL THEN 0 ELSE 1 END) AS neuro_not_NULL,
        SUM(CASE WHEN dental_value IS NULL THEN 1 ELSE 0 END) AS dental_NULL,
        SUM(CASE WHEN dental_value IS NULL THEN 0 ELSE 1 END) AS dental_not_NULL

    FROM @PHARMA
) AS derived

1 个答案:

答案 0 :(得分:1)

你可以简化为

SELECT  CAST (COUNT (CASE WHEN optical is not null 
                          THEN optical_value END)
              * 100.0 / COUNT(*) AS decimal(5,2) ) as optical_fill_rate
FROM    @PHARMA