在值范围内计算STARS的数量

时间:2012-02-06 21:11:06

标签: sql-server-2008 criteria

我需要在以下值中计算每个用户STARS总数的“星数”

数据库:MS SQL 2008 R2

STARAMOUNT1 = STAR score < 1.4

STARAMOUNT2 = STAR score BETWEEN 1.5 AND 2.4

STARAMOUNT3 = STAR score BETWEEN 2.5 AND 3.4

STARAMOUNT4 = STAR score BETWEEN 3.5 AND 4.4

STARAMOUNT5 = STAR score BETWEEN 4.5 AND 5.0

为每位用户提供大量明星的初始SQL是:

    SELECT Cast(Cast(Round(AVG(Cast(b.stars AS Float)),1)
 AS Numeric(25,1)) AS VarChar(25)) AS 'Stars' 
    FROM score b
        JOIN game_users a ON a.id = b.game_users_id
        GROUP BY a.username, a.current_state    

然后我需要在具有大量明星数量的用户数量的上述内容中进行计数

有人可以帮我这个吗? : - )

最好的问候

Stig: - )

2 个答案:

答案 0 :(得分:1)

这应该这样做,虽然我改变了你的初始查询的一部分,以符合你的要求:

;WITH UserStars AS
(
    SELECT a.username, ROUND(AVG(CAST(b.stars AS FLOAT)),1) Stars
    FROM score b
    JOIN game_users a ON a.id = b.game_users_id
    GROUP BY a.username
)
SELECT  CASE WHEN Stars < 1.4 THEN 'StarAmount1'
        WHEN Stars BETWEEN 1.4 AND 2.4 THEN 'StarAmount2'
        WHEN Stars BETWEEN 2.4 AND 3.4 THEN 'StarAmount3'
        WHEN Stars BETWEEN 3.4 AND 4.4 THEN 'StarAmount4'
        WHEN Stars BETWEEN 4.4 AND 5.0 THEN 'StarAmount5' ELSE 'AnotherStarAmount' END StarAmount,
        COUNT(*) Users
FROM UserStars
GROUP BY CASE WHEN Stars < 1.4 THEN 'StarAmount1'
         WHEN Stars BETWEEN 1.4 AND 2.4 THEN 'StarAmount2'
         WHEN Stars BETWEEN 2.4 AND 3.4 THEN 'StarAmount3'
         WHEN Stars BETWEEN 3.4 AND 4.4 THEN 'StarAmount4'
         WHEN Stars BETWEEN 4.4 AND 5.0 THEN 'StarAmount5' ELSE 'AnotherStarAmount' END

答案 1 :(得分:0)

这是一种方式,肯定有其他方式。

SELECT
    u.username, u.current_state,
    STARAMOUNT1 = SUM(CASE WHEN s.score < 1.4 THEN 1 ELSE 0 END),
    STARAMOUNT2 = SUM(CASE WHEN s.score BETWEEN 1.5 AND 2.4 THEN 1 ELSE 0 END),
    STARAMOUNT3 = SUM(CASE WHEN s.score BETWEEN 2.5 AND 3.4 THEN 1 ELSE 0 END),
    STARAMOUNT4 = SUM(CASE WHEN s.score BETWEEN 3.5 AND 4.4 THEN 1 ELSE 0 END),
    STARAMOUNT5 = SUM(CASE WHEN s.score > 4.5 THEN 1 ELSE 0 END)
FROM dbo.score AS s
INNER JOIN dbo.game_users AS u
ON u.id = s.game_users_id
GROUP BY u.username, u.current_state;