From和Having子句中的嵌套查询

时间:2016-02-07 08:17:23

标签: python sql

架构:

CREATE TABLE companies (
company_name varchar(200),
market varchar(200),
funding_total integer,
status varchar(20),
country varchar(10),
state varchar(10),
city varchar(30),
funding_rounds integer,
founded_at date,
first_funding_at date,
last_funding_at date,
PRIMARY KEY (company_name,market,city)
);

查询:

在“安全”市场中拥有/拥有最多创业公司数量的州(即市场栏中包含“安全”一词)是什么,列出所有关系?

代码:

db.executescript("""
    DROP VIEW IF EXISTS q3;

    select companies.state, count(*)as total
    from companies
    where companies.market like '%Security%'
    group by companies.state
    having count(*) = 
    (
    select max(countGroup) as maxNumber
    from (select C.state, count(*) as countGroup
        from companies as C
        where C.market like '%Security%'
        group by C.state)
     );

"""

编辑: 仍然存在错误,因为输出/结果为空。有什么想法吗?

2 个答案:

答案 0 :(得分:1)

试试这个。 (请调整RDBMS的语法)

select state, total from 
(    select companies.state, count(*)as total
from companies
where companies.market like '%Security%'
group by companies.state
) as countgroups
where total =
(
select max(countGroup) as maxNumber
from (select C.state, count(*) as countGroup
    from companies as C
    where C.market like '%Security%'
    group by C.state)
 );

可替换地:

select state, total from
(select companies.state, count(*)as total
from companies
where companies.market like '%Security%'
group by companies.state
) order by 2 desc
limit 1; --please adapt syntax of your RDBMS

答案 1 :(得分:0)

用括号括起子查询