带有CASE和MAX值的SQL查询

时间:2017-12-23 18:09:41

标签: sql sql-server tsql

客户可以购买多种产品,我在下面创建了一个查询,用于计算Workload对每个客户产品的使用情况。它有效。

但是,如何选择利用率最高的工作负载?我尝试了多种方法,但它似乎没有效果。

这是我得到的: enter image description here

这就是我想要的: enter image description here

with Usage as
    (
        select 
            [ID]
            ,[Workload]
            ,[QE]
            ,[EE]
            ,(CASE 
                WHEN QE <= 0 THEN '0'
                ELSE CAST([AE] as float) / [QE]
            END) as Utilization
        from [source].[Usage]
    )

select 
    O.[ID]
    ,O.[Workload]
    ,O.[QE]
    ,O.[EE]
    ,max(cast([Utilization] as decimal)) as 'Utilization'
FROM Usage O
Group by O.[ID], O.[Workload], O.[QE],O.[EE]

1 个答案:

答案 0 :(得分:2)

只需使用窗口功能。这是一种方式:

with Usage as (
      select [ID], [Workload], [QE], [EE],
             MAX(CASE WHEN QE <= 0 THEN 0 ELSE CAST([AE] as float) / NULLIF([QE], 0)
                 END) as Utilization
      from [source].[Usage] u
      group by [ID], [Workload], [QE], [EE]
     ) 
select u.*
from (select u.*, row_number() over (partition by id order by utilization desc) as seqnum
      from Usage u
     ) u
where seqnum = 1;