简体   繁体   English

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

[英]How to count two different columns in sql

I have a database which looks like this.我有一个看起来像这样的数据库。

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)

My task is to get the columns of dates, number of exams on that date, number of students who write an exam on that date.我的任务是获取日期列、该日期的考试数量、该日期参加考试的学生人数。 Something like Date - Exam Count - Student Count.类似日期 - 考试人数 - 学生人数。 I have done this but in two different queries.我已经这样做了,但在两个不同的查询中。

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 | ====================|

After I tried to combine these two queries into one and I got this, but it gives me the same count at every row, see the image below:在我尝试将这两个查询合并为一个之后,我得到了这个,但它在每一行都给了我相同的计数,请参见下图:

在此处输入图片说明

I know that's because of adding new table, but how do I make it work?我知道那是因为添加了新表,但我如何使它工作?

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

You've almost got it.你已经差不多了。 Just combine your two queries:只需结合您的两个查询:

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

NOTE: Not tested, no MySQL on current box注意:未测试,当前盒子上没有 MySQL

I think you want count(distinct) .我想你想要count(distinct) However, your tables don't seem to have unique ids, so my best guess is:但是,您的表似乎没有唯一的 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

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

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