我有两个问题:
第一:
select year, sum(count(id)*3);
我得到的错误是“字段列表中的未知列x.year”。
我希望查询充当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;
第二
我需要编写一个与没有外连接的情况相同的查询:
(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);
我尝试了以下但是没有用:
{{1}}
谢谢!
答案 0 :(得分:0)
尝试下面的第一个
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;
答案 1 :(得分:0)
我假设你有以下表::
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 |
+------------+------------+
那应该是你期待的!
答案 2 :(得分:0)
尝试以下
-- 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;