开发者

counting twice in a query, once using restrictions

Given the following tables:

Table1
[class]   [child]
 math      boy1
 math      boy2
 math      boy3
 art       boy1

Table2
[child]   [glasses]
 boy1       yes
 boy2       yes
 boy3       no

If I want to query for number of children per class, I'd do this:

SELECT class,开发者_Go百科 COUNT(child) FROM Table1 GROUP BY class

and if I wanted to query for number of children per class wearing glasses, I'd do this:

SELECT Table1.class, COUNT(table1.child) FROM Table1
LEFT JOIN Table2 ON Table1.child=Table2.child
WHERE Table2.glasses='yes' GROUP BY Table1.class

but what I really want to do is:

SELECT class, COUNT(child), COUNT(child wearing glasses)

and frankly I have no idea how to do that in only one query.

help?


You can try something like this (not syntax checked):

SELECT 
   class, 
   COUNT(distinct Table1.child), 
   SUM(IF(Table2.glasses='yes', 1, 0))
FROM Table1
LEFT JOIN Table2 ON Table1.child=Table2.child

It's a bit hacky and you may find it's just easier to do it in two queries but this technique has worked for me in a pinch


in MySQL you can do it something like this:

SELECT class, COUNT(child), SUM(IF(glasses = 'yes', 1, 0)


It is not a perfect solution, it is just a alternative solution,

SELECT class AS a, COUNT( child ) AS b
FROM Table1
GROUP BY class
UNION ALL SELECT COUNT( table1.child ) AS a, Table1.class AS b
FROM Table1
LEFT JOIN Table2 ON Table1.child = Table2.child
WHERE Table2.glasses = 'yes'
GROUP BY Table1.class

The output is :

a   b
art     1
math    3
1   art
2   math

In this, we may got some idea for develop more thing.


Maybe the post is 5 years old but I ahve also a solution.

Working with digits like 1 and 0 for yes/no and true/false will be easier for you.

A solution would be (if you change the yes's and no's to 1 and 0):

SELECT class,     
COUNT(distinct Table1.child) AS NumbofChilds,     
SUM(Table2.glasses) AS ChildswithGlasses 

FROM Table1 INNER JOIN Table2 ON Table1.child=Table2.child

GROUP BY class;

Syntax have to be checked, but I have a similar query for my tables and it works.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜