按范围SQL Server分组

时间:2015-04-28 21:19:10

标签: sql sql-server

UPDATE !!!!

我使用相应的输出构建了以下SQL查询:

enter image description here

enter image description here

我想有效地为每个聚合添加标签,如下所示:

coupon percent   |   income level
-----------------------------------
 .023434355      |   0-20000
 .054888999      |   20000-35000
 .010000002      |   35000-100000

有什么建议吗?

1 个答案:

答案 0 :(得分:3)

您可以在CASE上添加GROUP BY语句,例如

GROUP BY CASE 
    WHEN storeAvgIncome <= 20000 THEN '0-20000' 
    WHEN storeAvgIncome > 20000 AND storeAvgIncome <=  35000 THEN '20000-35000' 
    WHEN storeAvgIncome > 35000 AND storeAvgIncome <= 100000 THEN '35000-100000'
    END

然后将其添加到您的SELECT

SELECT 
    CASE 
        WHEN storeAvgIncome <= 20000 THEN '0-20000' 
        WHEN storeAvgIncome > 20000 AND storeAvgIncome <=  35000 THEN '20000-35000' 
        WHEN storeAvgIncome > 35000 AND storeAvgIncome <= 100000 THEN '35000-100000'
        END AS [income level]