SQL查询修改/优化

时间:2017-03-02 20:45:56

标签: sql sql-server sql-server-2008

我正在试图弄清楚如何将这3个查询变成一个具有百分比列的查询,这是我无法弄清楚的。有人可以帮忙吗?

Select DISTINCT a.ASSN As Association, SUM(tonnage_adjusted) as TotalTonnage        
From DeliveryTons d INNER JOIN ReapingGroups a ON d.reaping_code = a.REAPING_GROUP_CODE
WHERE reaping_code IS NOT NULL 
Group By a.ASSN
ORDER BY Association


Select DISTINCT a.ASSN As Association, SUM(tonnage_adjusted) as Monitored       
From DeliveryTons d INNER JOIN ReapingGroups a ON d.reaping_code = a.REAPING_GROUP_CODE
WHERE remarks = '' AND reaping_code IS NOT NULL 
Group By a.ASSN
ORDER BY Association


Select DISTINCT a.ASSN As Association, SUM(tonnage_adjusted) as NotMonitored        
From DeliveryTons d INNER JOIN ReapingGroups a ON d.reaping_code = a.REAPING_GROUP_CODE
WHERE remarks = 'NO_TICKET' AND reaping_code IS NOT NULL 
Group By a.ASSN
ORDER BY Association

1 个答案:

答案 0 :(得分:1)

这应该有用。

With Summary as (
    Select a.ASSN As Association
          ,SUM(tonnage_adjusted) as TotalTonnage
          ,SUM(case when remarks = '' THEN tonnage_adjusted ELSE NULL END) as Monitored
          ,SUM(case when remarks = 'NO_TICKET' THEN tonnage_adjusted ELSE NULL END) as NotMonitored
    From DeliveryTons d 
    INNER JOIN ReapingGroups a 
    ON d.reaping_code = a.REAPING_GROUP_CODE
    WHERE d.reaping_code IS NOT NULL 
    Group By a.ASSN
    )

SELECT Association
      ,TotalTonnage
      ,Monitored
      ,NotMonitored
      ,((Monitored/TotalTonnage) * 100) as pct_Monitored
    FROM Summary
    Order by Association