SQL子查询。不知道如何开始

时间:2016-04-19 21:48:24

标签: sql oracle

该表名为String readersNum = verseReaders.getJSONObject(0).getString("number"); ,其列为:id,fname,lname,state,jobtitle,salary,cat

我想显示50个州,Cat州值为Y的州的人数,Cat值为N的州的人数以及该州的总人数。四个列标题应为State,Yes,No和Total。

我知道我们应该使用子查询但不知道如何开始。

2 个答案:

答案 0 :(得分:2)

SELECT State
     , SUM(CASE WHEN Cat = 'Y' THEN 1 ELSE 0 END) as Yes
     , SUM(CASE WHEN Cat = 'N' THEN 1 ELSE 0 END) No
     , COUNT(*) as Total
  FROM PEOPLE
 GROUP BY STATE

答案 1 :(得分:0)

下面:

SELECT upper(p.state) State,
     (SELECT count(*) from PEOPLE p2 where p2.state = p.state and p2.cat = 'Y') Yes,
     (SELECT count(*) from PEOPLE p3 where p3.state = p.state and p3.cat = 'N') No,
     count(*) Total
FROM PEOPLE p
GROUP BY upper(state)

如果您对此有任何疑问,请随意提问。