getting sum using sql with multiple conditions

前端 未结 1 1198
粉色の甜心
粉色の甜心 2021-01-25 05:01

I m having data in columns as: -

  Process   Volume      TAT
  1            1        Pass
  1            2        Fail
  2            5        Fail
  2                  


        
相关标签:
1条回答
  • 2021-01-25 05:32

    For SQL Server, you can use CASE expressions to conditionally determine the amount you need to add, then SUM them together, like this:

    SELECT Process, SUM(Volume) AS TotalVolume, 
        SUM(CASE WHEN TAT = 'Pass' THEN Volume ELSE 0 END) AS Pass,
        SUM(CASE WHEN TAT = 'Fail' THEN Volume ELSE 0 END) AS Fail
    FROM (
         -- Dummy data here for testing
        SELECT 1 AS Process, 1 as Volume, 'Pass' AS TAT
        UNION SELECT 1, 2, 'Fail'
        UNION SELECT 2, 5, 'Fail'
        UNION SELECT 2, 5, 'Pass'
        UNION SELECT 3, 1, 'Pass'
        UNION SELECT 4, 6, 'Fail'
        UNION SELECT 4, 4, 'Pass'
    ) MyTable
    GROUP BY Process
    ORDER BY Process
    

    For Microsoft Access, CASE isn't supported, so you can use SWITCH or IIF, like so:

    SUM(IIF(TAT = 'Pass', Volume, 0)) AS Pass
    
    0 讨论(0)
提交回复
热议问题