-1

我正在做我的最后一个项目,这是返回所有 id、姓名和日期列表的查询。

select 
 c.id as id, i.full_name as n, day as d
 from
 (instructors i
 inner join courses c ON c.instructor_id = i.id)
 inner join exam_schedules e ON c.id = e.course_id

结果示例:

id  name    day
9977    SCOTT, RAYMOND C.   wednesday
9467    FERNANDEZ, CYNTHIA E.   wednesday
9468    FERNANDEZ, CYNTHIA E.   wednesday
9493    FERNANDEZ, CYNTHIA E.   wednesday
9538    STEPHENS, RONNIE T. wednesday
9539    MYERS, RONNIE Y.    wednesday
9554    GARRISON, EUGENE A. wednesday

如何获取所有 ID 的列表和 name+day 组合的计数?

上面的例子应该产生:

9977    1
9467    3
9468    3
9493    3
9538    1
9539    1
9554    1
4

2 回答 2

1

为了清楚起见,我使用了临时表。可以将其合并到一个查询中,但如果没有真正的模式,就很难做到:

CREATE TABLE tmp2 ( id int, name_day varchar(80) );

INSERT INTO tmp2 (id, name_day) (SELECT c.id AS id, CONCAT(i.full_name, i.day) AS name_day
     FROM (instructors i
         INNER JOIN courses c ON c.instructor_id = i.id)
         INNER JOIN exam_schedules e ON c.id = e.course_id
         );

SELECT id, counter FROM 
    (SELECT name_day, count(*) AS counter FROM tmp2 GROUP BY name_day) AS t1
    INNER JOIN
    tmp2
    ON t1.name_day = tmp2.name_day;

DROP TABLE tmp2;
于 2012-05-26T06:27:51.290 回答
0

在不了解您的架构的情况下,很难确定什么是最佳查询;但本质是您需要在子查询中计算每天的计数,然后将结果与表连接以产生所需的输出。例如:

SELECT   c.id, ctbl.total
FROM     instructors    AS i
  JOIN   courses        AS c ON c.instructor_id = i.id
  JOIN   exam_schedules AS e ON e.course_id     = c.id
  JOIN (
    SELECT   day
      ,      COUNT(*) AS total
    FROM     instructors    AS i
      JOIN   courses        AS c ON c.instructor_id = i.id
      JOIN   exam_schedules AS e ON e.course_id     = c.id
    GROUP BY day
  ) AS ctbl USING (day)
于 2012-05-26T06:37:20.953 回答