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

后端 未结 3 475
灰色年华
灰色年华 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:55

    This is a pivot table query. (Search on that if you require further info.)

    The query structure you want is something along the lines of the following:

    SELECT  groupname,
            SUM(CASE WHEN subsys = 'NORM' THEN jobs ELSE 0 END) AS NormJobs,
            SUM(CASE WHEN subsys = 'NORM' THEN cpu ELSE 0 END) AS NormCpu,
            SUM(CASE WHEN subsys = 'SYS7' THEN jobs ELSE 0 END) AS Sys7Jobs,
            SUM(CASE WHEN subsys = 'SYS7' THEN cpu ELSE 0 END) AS Sys7Cpu,
            SUM(CASE WHEN subsys NOT IN ('NORM', 'SYS7') THEN jobs ELSE 0 END) AS OtherJobs,
            SUM(CASE WHEN subsys NOT IN ('NORM', 'SYS7') THEN cpu ELSE 0 END) AS OtherCpu
    FROM    ???
    GROUP BY groupname
    
    0 讨论(0)
  • 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+.

    0 讨论(0)
  • 2021-01-18 08:05

    I don't understand the problem with sub-querying, it seems like it should be just as fast:

    select
        sub.gn as groupname,
        sum(sub.nj) as NormJobs, sum(sun.nc) as NormCpu,
        sum(sub.sj) as Sys7Jobs, sum(sub.sc) as Sys7Cpu
      from (
          select
              groupname as gn,
              sum(jobs) as nj, sum(cpu) as nc,
              0 as sj, 0 as sc
            from tbl
              where subsys = 'NORM'
              group by groupname
            union all select
                groupname as gn,
                0 as nj, 0 as nc,
                sum(jobs) as sj, sum(cpu) as sc
              from tbl
              where subsys = 'SYS7'
              group by groupname
        ) as sub
        group by sub.gn
        order by 1
    
    0 讨论(0)
提交回复
热议问题