如何计算 sql 中的两个不同列

How to count two different columns in sql

我有一个看起来像这样的数据库。

school
  exam
    firstname: varchar(40)
    name: varchar(40)
    lesson: varchar(30)
    item: smallint(6)
  lessons
    lesson: varchar(30)
    grade: smallint(6)
    abc: char(1)
    edate: date
  students
    firstname: varchar(40)
    name: varchar(40)
    grade: smallint(6)
    abc: char(1)

我的任务是获取日期列、该日期的考试次数、该日期参加考试的学生人数。类似于日期 - 考试人数 - 学生人数。我已经这样做了,但是在两个不同的查询中。

SELECT l.edate, COUNT(l.edate) AS Exams
FROM lessons l
WHERE (l.edate IS NOT NULL)
GROUP BY l.edate
ORDER BY l.edate DESC

Result: edate Exams | ==================| 2020-05-24 | 1 | 2020-05-23 | 1 | 2020-05-22 | 2 | 2020-05-20 | 1 | 2020-05-19 | 1 | 2020-05-18 | 1 | 2020-05-16 | 2 | 2020-05-15 | 2 | 2020-05-14 | 5 | ==================|

SELECT l.edate, COUNT(l.edate) AS Writing
FROM lessons l
JOIN students s
ON (l.abc = s.abc) AND (l.grade = s.grade)
WHERE (l.edate IS NOT NULL)
GROUP BY l.edate
ORDER BY l.edate DESC

Result: edate Writing | ====================| 2020-05-24 | 23 | 2020-05-23 | 27 | 2020-05-22 | 40 | 2020-05-20 | 30 | 2020-05-19 | 27 | 2020-05-18 | 25 | 2020-05-16 | 52 | 2020-05-15 | 34 | 2020-05-14 | 116 | ====================|

在我尝试将这两个查询合并为一个查询后,我得到了这个,但它在每一行都给我相同的计数,请参见下图:

我知道这是因为添加了新的 table,但我该如何让它发挥作用?

SELECT l.edate, COUNT(l.edate) AS Exams, COUNT(s.firstname) AS Writing
FROM lessons l
JOIN students s
ON (l.abc = s.abc) AND (l.grade = s.grade)
WHERE (l.edate IS NOT NULL)
GROUP BY l.edate
ORDER BY l.edate DESC

我想你想要 count(distinct)。但是,您的表似乎没有唯一 ID,所以我最好的猜测是:

SELECT l.edate, COUNT(*) AS Exams, COUNT(DISTINCT s.firstname) AS Writing
FROM lessons l JOIN
     students s
     ON l.abc = s.abc AND l.grade = s.grade
WHERE l.edate IS NOT NULL
GROUP BY l.edate
ORDER BY l.edate DESC

你快搞定了。只需结合您的两个查询:

SELECT E.edate, Exams, Writings FROM
(
  SELECT l.edate, COUNT(l.edate) AS Exams
  FROM lessons l
  WHERE (l.edate IS NOT NULL)
  GROUP BY l.edate) As E
JOIN
(
  SELECT l.edate, COUNT(l.edate) AS Writings
  FROM lessons l
  JOIN students s
  ON (l.abc = s.abc) AND (l.grade = s.grade)
  WHERE (l.edate IS NOT NULL)
  GROUP BY l.edate) As W ON E.edate=W.edate
ORDER BY E.edate

注意:未测试,当前框

上没有MySQL