简体   繁体   English

MySQL多个聚合函数和外部联接

[英]MySQL multiple aggregate functions and outer joins

I have two questions: 我有两个问题:

First: 第一:

select x.year, sum(x.cnt)
from (select count(id)*3 as cnt from takes where year = 2009 group by year) x
group by x.year;

The error I get is "Unknown column x.year in field list. I would like the query to act as select year, sum(count(id)*3); 我得到的错误是“字段列表中的未知列x.year。我希望查询充当select year, sum(count(id)*3);

Second: 第二:

I need to write a query that does the same as the following without outer join: 我需要编写一个查询,该查询无需外部联接即可执行以下操作:

select instructor.id, name, count(teaches.id) as 'Number of Sections'
from instructor natural left outer join teaches
group by teaches.id, name, instructor.id
order by instructor.id asc;

I tried the following but it did not work: 我尝试了以下操作,但没有成功:

(select instructor.id, name, count(teaches.id) as 'Number of Sections'
from instructor, teaches
where instructor.id = teaches.id
group by teaches.id, name, instructor.id)
union
(select i.id, i.name, count(t.id)
from instructor i, teaches t
where i.id not in (select id from teaches)
group by t.id, i.name, i.id);

Thank you! 谢谢!

Try below for the first one 在下面尝试第一个

select x.year, sum(x.cnt)
from (select count(id)*3 as cnt, year from takes where year = 2009 group by year) x
group by x.year;

I assume you have below table:: 我假设您有下表:

mysql> select * from takes;
+------+------------+
| id   | year       |
+------+------------+
|  101 | 2017-01-01 |
|  102 | 2015-01-01 |
|  103 | 2014-01-01 |
|  103 | 2015-01-01 |
|  101 | 2015-01-01 |
|  101 | 2009-01-01 |
|  102 | 2009-01-01 |
|  102 | 2009-01-01 |
|  101 | 2009-01-01 |
|  101 | 2009-01-01 |
|  103 | 2009-01-01 |
+------+------------+

select x.year, sum(x.cnt) from (select count(id)*3 as cnt, year from takes where year(year) = "2009" group by year)x group by x.year;

+------------+------------+
| year       | sum(x.cnt) |
+------------+------------+
| 2009-01-01 |         18 |
+------------+------------+

That's should be you expect! 那应该是您所期望的!

Try the following 尝试以下

-- 1
select x.year, sum(x.cnt)
from
  (
    select year,count(id)*3 as cnt
    from takes
    where year = 2009
    group by year
  ) x
group by x.year;

-- 2.1
select i.id, i.name, count(t.id) as 'Number of Sections'
from instructor i
join teaches t on i.id = t.id
group by i.id, i.name

union all

select id, name, 0 -- I think here is 0 sections
from instructor
where id not in (select id from teaches);

-- 2.2 - I think it also should work
select i.id, i.name, count(t.id) as 'Number of Sections'
from instructor i
left join teaches t on i.id = t.id
group by i.id, i.name;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM