进行比较un SQL请求

时间:2018-05-04 13:00:16

标签: sql flask psql

我有两张表,定义如下:

STATE(NAME varchar,
      POSTALCODE char) 

NB_PRISONERS_STATE(AGE int,
                   SEX char(1), 
                   POSTAL_CODE char, 
                   YEAR integer, 
                   NB integer,
                   LEVEL integer)

这两个表可以与STATE.postalcode=NB_PRISONERS_STATE.POSTAL_CODE

链接

年龄是整数,只能是1 2或3
等级是整数,只能是1或2 性是char,只能是'F'或'M'。

我想提出一个请求,为我提供给定STATE.name YEAR的所有LEVEL,给定Select STATE.name from STATE,NB_PRISONERS_STATE where STATE.postalcode=NB_PRISONERS_STATE.POSTAL_CODE CASE WHEN SUM(select NB_PRISONERS_STATE.nb where NB_PRISONERS_STATE.sexe='H')>SUM(select NB_PRISONERS_STATE.nb where NB_PRISONERS_STATE.sexe='F') ,其中男性多于女性入狱。

我试过

newsContainer.innerHTML = x;

1 个答案:

答案 0 :(得分:0)

像这样的东西

SELECT S.NAME
FROM NB_PRISONERS_STATE  P 
INNER JOIN STATE S ON P.POSTAL_CODE=S.POSTALCODE 
WHERE P.YEAR = 2017 AND P.LEVEL=1
GROUP BY S.NAME 
HAVING SUM(CASE WHEN P.SEX='M' THEN 1 ELSE 0 END) > SUM(CASE WHEN P.SEX='F' THEN 1 ELSE 0 END)

相应更改:

WHERE P.YEAR = 2017 AND P.LEVEL=1

根据您的要求:

  

给定YEAR的所有STATE.name,给定的LEVEL