SQL Server:从表中选择值的范围并对其进行计算

时间:2019-01-09 04:43:14

标签: sql sql-server range case

我有这张桌子

enter image description here

具有3列

Machine Name | memory | date

我想:

  1. 如果内存值在一定范围内,请选择这些内存的平均值
  2. 我想知道它达到该范围的频率

这是我的主意,但是:

SELECT
    MachineName, 
    CASE 
       WHEN Memory >= 75 AND Memory < 85 
          THEN AVG(Memory) AS Memory75to85,
               COUNT((MachineName)) AS Frequency75to85,
       WHEN Memory >= 85 AND Memory < 95 
          THEN AVG(Memory) AS Memory85to95,
               COUNT((MachineName)) AS Frequency85to95 
       WHEN Memory >= 95 AND Memory <= 100
          THEN AVG(Memory) AS Memory95to100,
               COUNT((MachineName)) AS Frequency95to100
       ELSE
          0, CounterDateTime
    END
FROM 
    Table
GROUP BY 
    MachineName

但是它似乎不起作用。我想要的列结果是:

| Name | Memory75to85 | Frequency75to85 | Memory85to95 | Frequency85to95 | Memory95to100 | Frequency95to100 | date |

有人愿意帮助吗?

2 个答案:

答案 0 :(得分:2)

我认为您要在此处使用的是条件聚合:

SELECT
    MachineName,
    CounterDateTime,
    AVG(CASE WHEN Memory >= 75 AND Memory < 85 THEN Memory END) AS Memory75to85,
    COUNT(CASE WHEN Memory >= 75 AND Memory < 85 THEN 1 END) AS Frequency75to85,
    AVG(CASE WHEN Memory >= 85 AND Memory < 95 THEN Memory END) AS Memory85to95,
    COUNT(CASE WHEN Memory >= 85 AND Memory < 95 THEN 1 END) AS Frequency85to95,
    AVG(CASE WHEN Memory >= 95 AND Memory <= 100 THEN Memory END) AS Memory95to100,
    COUNT(CASE WHEN Memory >= 95 AND Memory <= 100 THEN 1 END) AS Frequency95to100
FROM yourTable
GROUP BY
    MachineName,
    CounterDateTime;

当前方法的一个主要问题是CASE表达式必须生成单个标量值。它不能输出两个不同的值。因此,在上面的查询中,我们根据内存范围获取条件平均值和计数以生成所需的输出。

答案 1 :(得分:0)

您可以尝试使用以下条件聚合-

Select  
   MachineName, 
   avg(CASE WHEN Memory >=75 AND Memory <85 THEN Memory end) AS Memory75to85,
   count(CASE WHEN Memory >=75 AND Memory <85 THEN MachineName end) AS Frequency75to85,
   avg(case when Memory >=85 AND Memory <95 THEN Memory end) AS Memory85to95,
   count(case when Memory >=85 AND Memory <95 THEN MachineName end) AS Frequency85to95 
   avg(case WHEN Memory >=95 AND Memory <=100 THEN Memory end) AS Memory95to100,
   count(case WHEN Memory >=95 AND Memory <=100 THEN MachineName end) AS Frequency95to100,
   cast(CounterDateTime as date) as Date
From Table
Group by MachineName,cast(CounterDateTime as date)