1

我想在我所在的位置显示这样的GROUP数据DATE

Date        Star1   Star2   Star3   Star4   Star5
2012-10-25  null    null    null     1       1

我的当前表有三 (3) 列,显示:

ID DATE        RATING
5  2012-10-25    4
6  2012-10-25    5

我正在使用此查询来尝试实现上述数据:

SELECT 
    DATE,
    CASE
        WHEN RATING = 1 THEN 1
        ELSE NULL
    END AS STAR1,
    CASE
        WHEN RATING = 2 THEN 1
        ELSE NULL
    END AS STAR2,
    CASE
        WHEN RATING = 3 THEN 1
        ELSE NULL
    END AS STAR3,
    CASE
        WHEN RATING = 4 THEN 1
        ELSE NULL
    END AS STAR4,
    CASE
        WHEN RATING = 5 THEN 1
        ELSE NULL
    END AS STAR5
FROM
    table1
WHERE
    DATE = '2012-10-25'
GROUP BY DATE
ORDER BY DATE

这只会吐出一个评级:

Date        Star1   Star2   Star3   Star4   Star5
2012-10-25  null    null    null    null      1

就像它不是在日期上进行分组一样,我该如何实现呢?

4

2 回答 2

3

MySQL 允许这样的查询有点令人惊讶,因为 GROUP BY 没有涵盖 SELECT 列表中的所有非聚合列。

如果您将 CASE 语句包装成计数,那么我认为您最终会得到您想要的:

SELECT 
    DATE,
    COUNT(CASE
        WHEN RATING = 1 THEN 1
        ELSE NULL
    END) AS STAR1,
    COUNT(CASE
        WHEN RATING = 2 THEN 1
        ELSE NULL
    END) AS STAR2,
    COUNT(CASE
        WHEN RATING = 3 THEN 1
        ELSE NULL
    END) AS STAR3,
    COUNT(CASE
        WHEN RATING = 4 THEN 1
        ELSE NULL
    END) AS STAR4,
    COUNT(CASE
        WHEN RATING = 5 THEN 1
        ELSE NULL
    END) AS STAR5
FROM
    table1
WHERE
    DATE = '2012-10-25'
GROUP BY DATE
ORDER BY DATE

请让我知道您如何使用这种方法。

于 2012-12-18T21:06:03.237 回答
1
SELECT 
DISTINCT DATE, 
(SELECT COUNT(RATING) FROM Table1 WHERE RATING = '1') AS Star1,
(SELECT COUNT(RATING) FROM Table1 WHERE RATING = '2') AS Star2,
(SELECT COUNT(RATING) FROM Table1 WHERE RATING = '3') AS Star3,
(SELECT COUNT(RATING) FROM Table1 WHERE RATING = '4') AS Star4,
(SELECT COUNT(RATING) FROM Table1 WHERE RATING = '5') AS Star5
FROM 
Table1
WHERE 
DATE = '2012-10-25'
GROUP BY DATE
ORDER BY DATE
于 2012-12-18T21:34:43.230 回答