带有分组的单列表中的 MySql 多列选择

Posted

技术标签:

【中文标题】带有分组的单列表中的 MySql 多列选择【英文标题】:MySql Multiple Column SELECT from Single Column Table with Grouping 【发布时间】:2012-12-06 03:46:54 【问题描述】:

我想在DATEGROUP 上显示这样的数据:

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

好像不是在 Date 上进行 GROUPing,我该如何实现呢?

【问题讨论】:

【参考方案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

【讨论】:

你不想(或不需要)一个 DISTINCT 子句。如果您要使用子选择,您需要确保它们是相关的。【参考方案2】:

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

请告诉我你是如何使用这种方法的。

【讨论】:

以上是关于带有分组的单列表中的 MySql 多列选择的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Hypersql 数据库(HSQLDB)中选择多列但仅按一列分组?

将 LinQ 与多列分组一起使用

如何解决oracle sql中的单分组问题

从 SelectInput (R Shiny) 中的分组选项列表中获取组标签

Sql通过分组多列来选择

分组多列时如何选择最大值或最后一条记录? [复制]