0

场景:我想进行一个查询,该查询可以返回来自同一列但条件不同的两个或多个字段,以便我可以计算数据。

SQL:

SELECT
       FROM_UNIXTIME(news_date, '%Y-%m-%d') AS `DATE`,
       COUNT(news_slant=1) AS `Neutral`,
       COUNT(news_slant=2) AS `Positive`,
       COUNT(news_slant=3) AS `Negative`
FROM tbl_news
GROUP BY `news_date`
ORDER BY `news_date`
4

3 回答 3

1

通过使用case内部count

SELECT
FROM_UNIXTIME(news_date, '%Y-%m-%d') AS `DATE`,
COUNT(case news_slant when 1 then 1 else null end) AS `Neutral`,
COUNT(case news_slant when 2 then 1 else null end) AS `Positive`,
COUNT(case news_slant when 3 then 1 else null end) AS `Negative`
FROM tbl_news
GROUP BY `news_date`
ORDER BY `news_date`
于 2013-09-17T04:45:28.953 回答
1

用例声明:

SELECT FROM_UNIXTIME(news_date, '%Y-%m-%d') AS `DATE`,
    COUNT(CASE WHEN news_slant=1 THEN 1 ELSE null END) AS Neutral,
    COUNT(CASE WHEN news_slant=2 THEN 1 ELSE null END) AS Positive,
    COUNT(CASE WHEN news_slant=3 THEN 1 ELSE null END) AS Negative ,
FROM MyTable
GROUP BY news_date
ORDER BY news_date
于 2013-09-17T04:45:59.973 回答
0

您可以使用标准IF条款。 COUNT()只会计算非空值。

SELECT 
FROM_UNIXTIME(news_date, '%Y-%m-%d') AS DATE, 
COUNT(IF(news_slant=1,1,NULL)) AS Neutral, 
COUNT(IF(news_slant=2,1,NULL)) AS Positive, 
COUNT(IF(news_slant=3,1,NULL)) AS Negative 
FROM tbl_news 
GROUP BY news_date 
ORDER BY news_date
于 2013-09-17T04:49:25.407 回答