我遇到的问题是,在没有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'
并且需要在SSRS中填充三个不同的图表。我能弄明白的唯一方法是编写15种不同的选择语句,但我觉得应该有一种更简单,更有效的方法来做到这一点。
谢谢!
答案 0 :(得分:1)
我喜欢使用cross apply
:
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
子句。
答案 1 :(得分:0)
为每个组使用条件聚合:
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'
答案 2 :(得分:0)
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