简体   繁体   中英

MySQL query, subquery, distinct, count,

Employees table
Name. New.
Shadab. Yes
Ali. No
Shadab. Yes
Results
Name. New(Yes). New(No)
Shadab. 2. 0
Ali. . 1

How can get this result from Employees Table? Using MySQL.

Just count Yes and No of New Column.

SELECT DISTINCT
    a.name, 
    coalesce(yes.numbers, 0), 
    coalesce(no.numbers, 0) 
FROM employees AS a
    LEFT JOIN (SELECT name, count(name) AS numbers FROM employees WHERE new = 'Yes' GROUP BY name) AS yes ON (a.name = yes.name)
    LEFT JOIN (SELECT name, count(name) AS numbers FROM employees WHERE new = 'No' GROUP BY name) AS no ON (a.name = no.name)

or with SUM and IF:

SELECT
    name,
    SUM(IF(new = 'Yes', 1, 0)) as yes_num,
    SUM(IF(new = 'No', 1, 0)) as no_num
FROM employees
GROUP BY name

here you can check the result

Here is your required Query:

SELECT 
Name,
SUM(CASE WHEN New='Yes' THEN 1 ELSE 0 END) as NEW_Yes,
SUM(CASE WHEN New!='Yes' THEN 1 ELSE 0 END) as NEW_No 
FROM `employees` 
GROUP BY Name

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