如何根据我在查询中计算的内容的范围进行分组?

时间:2015-10-21 16:04:40

标签: sql sql-server sql-server-2014-express

USE [IMTsimulations]
GO

SELECT SUM(CASE WHEN Xa BETWEEN 90 and 130 THEN 1 ELSE 0 end)/SUM(1) AS Xa_PIR2
  FROM [dbo].[Simulations]
  WHERE [dbo].[Simulations].[ExperimentID] IN (
    SELECT [ExperimentID] FROM [dbo].[Parameters] WHERE [SensorError] = 1 AND [ExogDEXCurve] <> 4 AND [ControlRange] = 2
  )
/*GROUP BY Xa_PIR2 WHERE Xa_PIR2 < .6, Xa_PIR2 BETWEEN .6 AND .8, Xa_PIR2 BETWEEN .8 AND 1 

My attempt at the group, obviously doesn't work. */
GO

我知道我可以做一个SELECT FROM PERCENT_IN_RANGE_TABLE,有点像here,但我没有这样的表。我想在飞行中这样做,因为我只会做一次这种特定的分析。

理想情况下,我会在每个“时间范围”组中进行一定比例的实验。我想知道实验的百分比(由ExperimentID唯一标识)的时间范围小于60%,范围内有60-80%的时间百分比,以及范围内80-100%的时间百分比。

3 个答案:

答案 0 :(得分:0)

首先使用CTE计算数据,然后将其分组到选择

WITH calculatedSimulations
AS
(
  SELECT SUM(CASE WHEN Xa BETWEEN 90 and 130 THEN 1 ELSE 0 end)/SUM(1) AS Xa_PIR2
  FROM [dbo].[Simulations]
  WHERE [dbo].[Simulations].[ExperimentID] IN (
    SELECT [ExperimentID] FROM [dbo].[Parameters] WHERE [SensorError] = 1 AND [ExogDEXCurve] <> 4 AND [ControlRange] = 2
  )
)
SELECT Xa_PIR2, 
       COUNT(*) as count -- for example!
FROM calculatedSimulations
GROUP BY 
   CASE WHEN Xa_PIR2 < 0.6 THEN 1
   CASE WHEN Xa_PIR2 >= 0.6 AND Xa_PIR2 < 0.8 THEN 2
   CASE WHEN Xa_PIR2 >= 0.8 THEN 3
END

答案 1 :(得分:0)

您是否尝试按案例陈述进行分组?

SELECT (CASE WHEN Xa_PIR2 < 0.6 THEN 'GROUP1'
             WHEN Xa_PIR2 < 0.8 THEN 'GROUP2'
             WHEN Xa_PIR2 < 1 THEN 'GROUP3'
        END) as grp, COUNT(*) as num, AVG(Xa_PIR2) as avg_in_group
FROM (SELECT AVG(CASE WHEN s.Xa BETWEEN 90 and 130 THEN 1.0 ELSE 0 end) AS Xa_PIR2
      FROM [dbo].[Simulations] s
      WHERE s.[ExperimentID] IN 
                (SELECT p.[ExperimentID]
                 FROM [dbo].[Parameters] p
                 WHERE p.[SensorError] = 1 AND p.[ExogDEXCurve] <> 4 AND p.[ControlRange] = 2
               )
     ) s
GROUP BY (CASE WHEN Xa_PIR2 < 0.6 THEN 'GROUP1'
               WHEN Xa_PIR2 < 0.8 THEN 'GROUP2'
               WHEN Xa_PIR2 < 1 THEN 'GROUP3'
          END);

有关查询的一些注释:

  • AVG()是一个聚合函数。你不需要做两笔钱,除非你真的非常想要。
  • CASE语句按顺序处理条件,因此您无需使用BETWEEN
  • 我总是在小数点前加上“0”,以防止无意的错误或误读查询。
  • 包括该组的平均值可以增强有关值分布的信息。
  • 表别名是个好主意。

答案 2 :(得分:-1)

试试这种事。

select this, sum(that) sumOfThat
from (
select case when whatever then 'fred' else 'barney' end this
, case when whatever then 0 else 1 end that
) temp
group by this