MSSQL中的Select和Group Number范围

时间:2018-05-04 09:26:54

标签: sql sql-server

    SELECT
    CASE
        WHEN Vote BETWEEN 1 and 6 THEN '1-8'
        WHEN Vote BETWEEN 7 and 8 THEN '7-8'
        WHEN Vote BETWEEN 9 and 10 THEN '9-10'
    END AS Vote_range,
    COUNT(*) AS count
    FROM CaseRatingVote
    GROUP BY Vote_range
GO

如何在MSSQL中完成这项工作我需要一个不同数字范围的组。

4 个答案:

答案 0 :(得分:2)

使用SELECTGROUP BY中完全相同的表达式。

SELECT
    CASE
        WHEN Vote BETWEEN 1 and 6 THEN '1-8'
        WHEN Vote BETWEEN 7 and 8 THEN '7-8'
        WHEN Vote BETWEEN 9 and 10 THEN '9-10'
    END AS Vote_range,
    COUNT(*) AS count
FROM 
    CaseRatingVote
GROUP BY 
    CASE
        WHEN Vote BETWEEN 1 and 6 THEN '1-8'
        WHEN Vote BETWEEN 7 and 8 THEN '7-8'
        WHEN Vote BETWEEN 9 and 10 THEN '9-10'
    END

或者,作为替代方案,首先计算分组列(不分组),然后在外部范围内按该列分组。这种方法更适合维护。

;WITH CTE AS
(
    SELECT
        CASE
            WHEN Vote BETWEEN 1 and 6 THEN '1-8'
            WHEN Vote BETWEEN 7 and 8 THEN '7-8'
            WHEN Vote BETWEEN 9 and 10 THEN '9-10'
        END AS Vote_range
    FROM 
        CaseRatingVote
)
SELECT
    Vote_range,
    COUNT(1)
FROM
    CTE AS C
GROUP BY
    C.Vote_range

答案 1 :(得分:1)

SELECT SUM(CASE WHEN Vote < 7 THEN 1 ELSE 0 END) AS [1-6],
        SUM(CASE WHEN Vote BETWEEN 7 AND 8 THEN 1 ELSE 0 END) AS [7-8],
        SUM(CASE WHEN Vote BETWEEN 9 AND 10 THEN 1 ELSE 0 END) AS [9-10],
        COUNT(*) AS count
 FROM CaseRatingVote

这是为我做这件事的简单方法。

答案 2 :(得分:0)

您可以使用CTE执行此操作:

with a as (
    SELECT
    CASE
        WHEN Vote BETWEEN 1 and 6 THEN '1-8'  --You may want to change this line!
        WHEN Vote BETWEEN 7 and 8 THEN '7-8'
        WHEN Vote BETWEEN 9 and 10 THEN '9-10'
    END AS Vote_range
    FROM CaseRatingVote
)
select  Vote_Range, count(*) as Row_Count
from    a
group by Vote_Range

答案 3 :(得分:0)

将查询包装在派生表中,group by结果:

select Vote_range, count(*) from
(
SELECT
CASE
    WHEN Vote BETWEEN 1 and 6 THEN '1-8'
    WHEN Vote BETWEEN 7 and 8 THEN '7-8'
    WHEN Vote BETWEEN 9 and 10 THEN '9-10'
END AS Vote_range
FROM CaseRatingVote
) dt
GROUP BY Vote_range