SQL statement, subquery count?

允我心安 提交于 2019-12-23 01:46:24

问题


I've got the following SQL tables

Department

|name|employees|

Employee

|name|gender|type|dead |
|John|male  |good|yes  |
|Mary|female|bad |no   |
|Joe |male  |ugly|maybe|

I would like to write a statement that returns

| type | n of employees | n of male employees | n of departments |

I've got

SELECT e.type, count(e), count(d) 
FROM Department d 
JOIN d.employees e
WHERE e.dead = maybe 
GROUP BY e.type

That's missing the 'n of male employees', of course. I'm stuck here, since I'm not sure, where to specify the additional clause e.gender = male.

I forgot to mention: HQL or criteria would be nice.


回答1:


Assuming your original query and schema is correct:

SELECT 
   e.type, 
   count(e), 
   count(d), 
   count (case when gender = 'male' then 1 else NULL end) AS NumberOfMaleEmployees
from Department d 
JOIN d.employees e
WHERE e.dead = 'maybe' 
GROUP BY e.type



回答2:


Just for reference:

SELECT 
   e.type, 
   count(e), 
   count(d), 
   sum(case when gender = 'male' then 1 else 0 end)
from Department d 
JOIN d.employees e
WHERE e.dead = 'maybe' 
GROUP BY e.type

works in HQL. Thanks everyone!



来源:https://stackoverflow.com/questions/7065916/sql-statement-subquery-count

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!