从SUM聚合尝试仅提取最大值

时间:2013-08-09 19:27:15

标签: sql sql-server sql-server-2008 sum max

/ *这个工作 - 显示昨天所有prod服务器的每小时会话* /

SELECT
SUM(active_sessions_peak + inactive_sessions_peak) 
AS TotalSessions, machine_name, time_stamp
FROM  ctrx_archive_system_perf
WHERE machine_name LIKE 'vmw-mc-%p%'
GROUP BY machine_name, time_stamp
ORDER BY machine_name

/ *这也可以 - 只返回每台服务器的午夜值* /

SELECT
SUM(active_sessions_peak + inactive_sessions_peak) 
AS TotalSessions, machine_name, time_stamp
FROM   vw_ctrx_archive_system_perf
WHERE machine_name LIKE 'vmw-mc-%p%'
AND 
time_stamp = CAST(DATEADD(d,-1,GETDATE()) AS DATE) 
GROUP BY machine_name, time_stamp
ORDER BY machine_name

最后一个给了我每个服务器的TotalSessions但只给了午夜一个。当然,这些会话数量当然会发生变化。我正在寻找的是每个machine_name的当天最高报告数。我研究了从SUM中获取MAX并尝试了临时表和子查询,但无法使这两种方法都起作用。

2 个答案:

答案 0 :(得分:0)

你可能想要这样的东西:

SELECT MAX(TotalSessions) as MaxSessions, machine_name
FROM (
  SELECT
  SUM(active_sessions_peak + inactive_sessions_peak) 
  AS TotalSessions, machine_name, time_stamp
  FROM  ctrx_archive_system_perf
  WHERE machine_name LIKE 'vmw-mc-%p%'
  GROUP BY machine_name, time_stamp
) AS machine_sums
GROUP BY machine_name
ORDER BY machine_name

哪个应该适用于任何理解SQL的数据库。如果您还需要获取相关的时间戳,事情会变得更加困难。

答案 1 :(得分:0)

;with cte1 as
    select
        sum(active_sessions_peak + inactive_sessions_peak) as TotalSessions,
        machine_name,
        time_stamp
    from ctrx_archive_system_perf
    where machine_name LIKE 'vmw-mc-%p%'
    group by machine_name, time_stamp
), cte2 as (
    select
        row_number() over (partition by machine_name order by TotalSessions desc) as row_num,
        *
    from cte1 
)
select
    TotalSessions, machine_name, time_stamp
from cte2
where row_num = 1