内连接 - 计数和字段总和

时间:2015-03-20 02:11:59

标签: sql

我有两个表editorstitle_editors,我正在尝试运行内部联接查询以显示所有编辑器以及他们编辑的书籍数量。我没有得到理想的结果,但是编辑了所有书籍的总和。如何列出所有编辑器的名称以及他们编辑和排列报表的书籍数量,以便首先列出编辑最多书籍的编辑器? SQLFIDDLE

查询

SELECT (e.first_name || ' ' || e.last_name) as Editor_Name, SUM(te.editor_order) as Books_Edited FROM editors e
INNER JOIN title_editors te ON te.editor_id = e.editor_id ORDER BY SUM(te.editor_order);

表架构

create table editors    (editor_id char(11) not null,   editor_lname varchar(40) not null,  editor_fname varchar(20) not null,  editor_positon varchar(12) null,    phone char(12) null,    address varchar(40) null,   city varchar(20) null,  state char(2) null, zip char(5) null,   ed_boss char(11) null );
create table title_editors  (editor_id char(11) not null,   title_id char(6) not null,  editor_order tinyint null);

2 个答案:

答案 0 :(得分:2)

除了关于CONCAT的评论之外,你还缺少你的GROUP BY,以及ORDER BY末尾的DESC,以便按照你想要的方式对它们进行排序。

SELECT
  CONCAT(e.editor_fname,' ',e.editor_lname),
  SUM(te.editor_order)
FROM
  editors e
INNER JOIN
  title_editors te
  ON te.editor_id = e.editor_id
GROUP BY
  e.editor_fname,
  e.editor_lname
ORDER BY
  SUM(te.editor_order) DESC;

http://sqlfiddle.com/#!9/47bd4/28

答案 1 :(得分:1)

http://sqlfiddle.com/#!9/47bd4/22

只需对结果进行分组。

SELECT (CONCAT(e.editor_fname,' ',e.editor_lname)) as Editor_Name
  , SUM(te.editor_order) as Books_Edited 
FROM editors e
INNER JOIN title_editors te 
  ON te.editor_id = e.editor_id 
GROUP BY e.editor_fname,e.editor_lname
ORDER BY Books_Edited;