根据同一字段中的值计算百分比

时间:2020-01-21 20:32:17

标签: sql-server

我正在使用SQL Server。我有一个不错的汇总表,就像您在下面看到的那样。我想为每个熟练程度填充(创建)“ Pct”字段。

| MeasurementScale | Grade | ProficiencyLevel | PL_Count | Pct |
|------------------|-------|------------------|----------|-----|
| Mathematics      |   6   | Did Not Meet     |    40    |     |
| Mathematics      |   6   | Approaches       |    86    |     |
| Mathematics      |   6   | Meets            |    83    |     |
| Mathematics      |   6   | Masters          |    42    |     |
| Mathematics      |   6   | Total            |   251    |     |

我基本上想要类似以下查询的内容,只是不知道如何编写。

SELECT SchoolName
      ,MeasurementScale
      ,Grade
      ,ProficiencyLevel 
      ,PL_Count
      ,(PL_Count / (SELECT PL_Count FROM #PL_Summary1920 WHERE ProficiencyLevel = 'Total')) as Pct
FROM #PL_Summary1920
GROUP BY SchoolName
        ,MeasurementScale
        ,Grade
        ,ProficiencyLevel 
        ,PL_Count

2 个答案:

答案 0 :(得分:1)

尝试一下:

SELECT MeasurementScale
  ,Grade
  ,ProficiencyLevel 
  ,PL_Count
  ,PL_Count * 1.0 / (SELECT PL_Count FROM #PL_Summary1920 WHERE ProficiencyLevel = 'Total') as Pct 
FROM #PL_Summary1920
GROUP BY SchoolName
    ,MeasurementScale
    ,Grade
    ,ProficiencyLevel 
    ,PL_Count

乘以1.0会将类型转换强制为十进制,因此您的百分比正确显示。比执行CAST或CONVERT更干净。

答案 1 :(得分:1)

SELECT  V1.*,
        CASE WHEN V2.PL_COUNT = 0 THEN 0
            ELSE V1.PL_Count * 1.0/ V2.PL_COUNT
        END AS  PCT
FROM    (
            SELECT  SchoolName,
                    MeasurementScale,
                    Grade,
                    ProficiencyLevel,
                    SUM(PL_Count)   AS  PL_Count
            FROM #PL_Summary1920 T1
            GROUP BY SchoolName
                    ,MeasurementScale
                    ,Grade
                    ,ProficiencyLevel 
        ) V1
LEFT JOIN   (
                SELECT  SchoolName,
                        MeasurementScale,
                        Grade,
                        SUM(TT.PL_Count)    AS  PL_COUNT
                FROM    #PL_Summary1920 TT
                WHERE   TT.ProficiencyLevel = 'Total'
                GROUP BY SchoolName,
                        MeasurementScale,
                        Grade
            ) V2 ON V2.SchoolName = V1.SchoolName
                    AND V2.MeasurementScale = V1.MeasurementScale
                    AND V2.Grade = V1.Grade