简体   繁体   中英

SQL Query Modification/Optimization

I am trying to figure out how to make these 3 queries into one with a percentage column that i havent been able to figure out. Can anyone assist?

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

This should work.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM