How do I combine two queries (union all) into one row?

后端 未结 3 495
灰色年华
灰色年华 2021-01-18 07:31

I have a tricky situation in trying to get information from multiple queries into a single row.

Consider the following table:

CpuUage:
    Time    ti         


        
3条回答
  •  难免孤独
    2021-01-18 07:58

    It's a typical pivot query - here's how you'd do it with CASE statements:

      SELECT t.group,
             SUM(CASE 
               WHEN t.subsys = 'NORM' THEN t.jobs 
               ELSE NULL
             END CASE) AS NormJobs,
             SUM(CASE 
               WHEN t.subsys = 'NORM' THEN t.cpu
               ELSE NULL
             END CASE) AS NormCpu,
             SUM(CASE 
               WHEN t.subsys = 'SYS7' THEN t.jobs 
               ELSE NULL
             END CASE) AS Sys7Jobs,
             SUM(CASE 
               WHEN t.subsys = 'SYS7' THEN t.cpu
               ELSE NULL
             END CASE) AS Sys7Cpu
        FROM CPUUSAGE t
    GROUP BY t.group
    

    Unfortunately, DB2's CASE statements need to end with END CASE, when Oracle/SQL Server/MySQL/Postgres doesn't. Well, PLSQL supports END CASE...

    There's also the PIVOT syntax, which is also supported on Oracle 11g, and SQL Server 2005+.

提交回复
热议问题