如何在范围(0-100),(100-200)中对列(旅行票价)进行分组

时间:2017-03-29 06:47:24

标签: sql-server-2008

我有一个SQL表,其中保留了预订记录。我必须分组否。基于票价范围(0-100),(100-200)的预订是明智的。票价最多3个小数点。请帮忙

1 个答案:

答案 0 :(得分:0)

这样的事情对你有用吗?

做出一些假设和基本的表定义

DECLARE @Booking TABLE(
     Id         INT IDENTITY(1,1)
    ,TravelFare DECIMAL(10,3)
)
INSERT INTO @Booking
        ( TravelFare )
VALUES
        ( 5 ),( 17 ),( 43 ),( 115 ),( 135 ),( 167 ),( 221 ),( 278 ),( 325 ),( 354 ),( 387 )


SELECT
     COUNT(X.TravelFare)    'Count'
    ,X.TravelFareGroup
FROM
(
SELECT
     TravelFare
    ,CASE
        WHEN TravelFare BETWEEN 0 AND 100 THEN '0-100'
        WHEN TravelFare BETWEEN 101 AND 200 THEN '101-200'
        WHEN TravelFare BETWEEN 201 AND 300 THEN '201-300'
        WHEN TravelFare BETWEEN 301 AND 400 THEN '301-400'
     END 'TravelFareGroup'
FROM
    @Booking
) X
GROUP BY
    TravelFareGroup