简体   繁体   中英

MySQL: How to SELECT COUNT two field names from originating from field name on the same table

SCENARIO: I want to make a query that can return two or more fields that came from the same column but different in criteria so that i can count the data.

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`

By using case inside 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`

Use Case Statement:

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

You can use a standard IF clause. COUNT() will only count non-null values.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM