Sql 查找特定值范围内的帐户数的最佳方法

Sql 查找特定值范围内的帐户数的最佳方法,sql,tsql,reporting-services,ssms,Sql,Tsql,Reporting Services,Ssms,我很难在没有20个不同选择的情况下找到属于某个值范围的所有帐户的最佳/最有效的方法 例如,我需要找到以下内容: Account Value Number of plans average value $100-$10000 $11000-$15000 $16000-$20000 $21000-$30000 $30000+ 所以现在我的查询基本上是针对每个值范围: SELECT COUNT (acct) AS 'Number of Plans' , A

我很难在没有20个不同选择的情况下找到属于某个值范围的所有帐户的最佳/最有效的方法

例如,我需要找到以下内容:

Account Value    Number of plans     average value
$100-$10000      
$11000-$15000
$16000-$20000
$21000-$30000
$30000+
所以现在我的查询基本上是针对每个值范围:

    SELECT COUNT (acct) AS 'Number of Plans'
     , AVG (Value) AS 'Average Value'
   FROM #RT1
  WHERE Value
        BETWEEN 0 AND 249999.99
        AND InstaCode = 'S'
SSR中需要填充三种不同的图表。我唯一能找到答案的方法是写15条不同的select语句,但我觉得应该有一种更简单、更有效的方法来做到这一点


谢谢

对每个组使用条件聚合:

          SELECT COUNT (case when Value
                BETWEEN 0 AND 249999.99
                 then value else null end) AS 'Number of Plans group 1',
COUNT (case when Value
                BETWEEN 2500000  AND 3000000
                 then value else null end) AS 'Number of Plans group 2',

                  AVG (case when Value
                    BETWEEN 0 AND 249999.99
                     then value else null end) AS 'Average Value 1st group', AVG (case when Value
                    BETWEEN 2500000 AND 3000000
                     then value else null end) AS 'Average Value 2nd group'...
    from #RT1
    where instacode='s'
我喜欢使用交叉申请:

SELECT v.grp, COUNT(acct) AS num_plans, AVG(value) as avg_value
FROM #RT1 t CROSS APPLY
     (VALUES (CASE WHEN value >= 100 and value < 10000 THEN '$100-$10000'
                   WHEN value < 15000 THEN '$11000-$15000'
                   WHEN value < 20000 THEN '$16000-$20000'
                   WHEN value < 30000 THEN '$21000-$30000'
                   ELSE '$30000+'
              END) as grp
     ) v(grp)
GROUP BY v.grp;

我不确定InstaCode='S'与结果有什么关系。它很容易添加到CASE表达式或WHERE子句中。

请参阅下面的内容,并告诉我这是否有效。现在尝试一下,谢谢。但我不知道如何解决我的问题。即使这样,我仍然需要15个不同的选择。不是一个选择-我会添加更多-查看更新-有什么问题吗?好的,我知道了,谢谢@stlblues123。您的问题明确要求在不同的行中输入值。我很惊讶你没有接受这个答案,而接受了另一个没有这样做的答案。
SELECT 
Case 
    When Value between 100 and 10000 Then '100 to 10000'
    When Value between 11000 and 15000 Then '11000 to 15000'
    When Value between 16000 and 20000 Then '16000 to 20000'
    When Value between 21000 and 30000 Then '21000 to 30000'
    When Value > 30000 Then '30000+'
End as AccountValue 
  COUNT (acct) AS NumberofPlans
 , AVG (Value) AS AverageValue
FROM #RT1
WHERE Value
    BETWEEN 0 AND 249999.99
    AND InstaCode = 'S'

Group by 
Case 
 When Value between 100 and 10000 Then '100 to 10000'
 When Value between 11000 and 15000 Then '11000 to 15000'
 When Value between 16000 and 20000 Then '16000 to 20000'
 When Value between 21000 and 30000 Then '21000 to 30000'
 When Value > 30000 Then '30000+'
End