Forum Discussion

Antonio2727's avatar
Antonio2727
Copper Contributor
Jan 31, 2024

Calculate AVG by type of product and group by month

Hi all, 

Any help how can i get the result on below table based on image attaches?

 

The pretented result:

MonthAVG (LeadTimeOfTypeFL)AVG (LeadTimeOfTypePH)
1715
21525

 

Thank you

    • Arshad440's avatar
      Arshad440
      Brass Contributor
      don't matter for the result.it consider on the basis of months
      • olafhelper's avatar
        olafhelper
        Bronze Contributor

        Arshad440 

        This should work for you:

        SELECT MONTH(T.Date) AS Month,
               AVG(CASE WHEN T.ProductType = 'FL' THEN T.LeadTime ELSE NULL END) AS LeadTimeOfTypeFL,
               AVG(CASE WHEN T.ProductType = 'PH' THEN T.LeadTime ELSE NULL END) AS LeadTimeOfTypePH
        FROM yourTable AS T
        GROUP BY MONTH(T.Date)
  • Arshad440's avatar
    Arshad440
    Brass Contributor
    hi,
    you can use this code

    SELECT Month,
    MAX(CASE WHEN ProductType='FL' THEN avg END) "AVG LeadTimeOFFL",
    MAX(CASE WHEN ProductType='PH' THEN avg END) "AVG LeadTimeoFPH"
    FROM (
    SELECT MONTH(DATE) Month,ProductType,AVG(LeadTime) avg FROM ProductTable GROUP BY MONTH(DATE),ProductType
    ) as fdfdf
    GROUP BY Month;

    use your table name instead of 'ProductTable' as table name

Resources