简体   繁体   中英

Combining two Count Queries into one

I have theses two queries

SELECT course,
COUNT(*) AS countp 
FROM table1 
WHERE pickout='Yes' 
GROUP BY course

SELECT course,
COUNT(*) AS countw
FROM table1
WHERE pickout='Yes' AND result='Won'
GROUP BY course

what I am trying to achieve is a table with three columns Course , Countp , Countw but I am having trouble combining the two into one query.

Basically I am looking for a list of course with number of picks and then number of wins.

In MySQL the result of conditions evaluate to 1 or 0 . You can sum that up

SELECT course, 
       sum(pickout='Yes') AS countp,
       sum(pickout='Yes' AND result='Won') AS countw
FROM table1 
GROUP BY course

Try the following SQL:

SELECT 
Course,
COUNT(*) AS CountP,
SUM(CASE WHEN result='Won' THEN 1 ELSE 0 END) AS CountW
FROM table1
WHERE pickout = 'Yes'
GROUP BY Course

try this:

select a.course,a.countp ,b.countw  from (SELECT course, COUNT(*) AS countp FROM table1 WHERE pickout='Yes' GROUP BY course)a full join 
(SELECT course, COUNT(*) AS countw FROM table1 WHERE pickout='Yes' AND result='Won' GROUP BY course)b
a.course=b.course

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