2015-04-28 193 views
2

UPDATE !!!!按範圍分組SQL Server

我有它相應的輸出內置下面的SQL查詢:

enter image description here

enter image description here

我想有效的標籤添加到每個聚合的象下面這樣:

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

有什麼建議嗎?

回答

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] 
+0

腳註:只要你能做到這一點作爲你的CASE語句[不包含一個聚合函數](http://stackoverflow.com/q/1208854/477563)。 –

+0

在我看到你的回覆之前,我實際上已經走得更遠了。現在我已經在case語句中設置了範圍,我如何才能將實際範圍本身顯示爲上述的有效行標籤?我不能簡單地將'dimStore.storeAvgIncome'添加到select語句,那麼如何獲得我的case語句,然後顯示相應行的值? – 92twinturboz

+0

查看編輯我的回答 – ChrisStillwell