gpt4 book ai didi

mysql - 使用计数表优化 SQL 查询多重连接

转载 作者:行者123 更新时间:2023-11-29 05:35:34 26 4
gpt4 key购买 nike

在我不向您展示表格的情况下,您是否有机会帮助优化此查询?

所有这些查询都派生 self 的原始表具有以下列,并且该表名为 laterec-students

--------------------------------------------------------------
| studentid | name | class | latetime | waived |
--------------------------------------------------------------
| ID1111STU | Stu 1 | 1A |2012-01-09 08:09:00 |Waived |



SELECT A.class, NoStudentsLate, 1xLATE, 2xLATE FROM (

SELECT
class,
count(DISTINCT studentid) AS NoStudentsLate
FROM `laterec-students`
WHERE waived!="Waived"
GROUP BY class

) AS A
LEFT JOIN (

SELECT class, count(distinct studentid) AS 1xLATE from (
SELECT `laterec-students`.class, `laterec-students`.studentid
FROM `laterec-students`
WHERE waived!="Waived"
GROUP BY studentid
HAVING count(studentid)=1) as temp
GROUP BY class
) AS B ON A.class=B.class

LEFT JOIN (
SELECT class, count(distinct studentid) AS 2xLATE from (
SELECT `laterec-students`.class, `laterec-students`.studentid
FROM `laterec-students`
WHERE waived!="Waived"
GROUP BY studentid
HAVING count(studentid)=2) as temp
GROUP BY class
) AS C ON A.class=C.class

这就是我想要完成的

---------------------------------------------------------------------
| Class | Total # of students late | # late 1 times | # late 2 times |
---------------------------------------------------------------------
| 1A | 5 | 3 | 2 |
| 1B | 3 | 3 | 0 |
---------------------------------------------------------------------

那么这意味着什么,在 1A 类,使用学生 ID 统计总共有 5 个学生迟到。这5人中,有3人迟到一次,2人迟到两次。

同样在1B类,共有3名学生迟到,而且他们都只迟到一次。

最佳答案

我希望我理解您的查询,但以下内容适用于我的 SQL Fiddle example .

SELECT
class,
SUM(cnt > 0) AS NoStudentsLate,
SUM(cnt = 1) AS 1xLate,
SUM(cnt = 2) AS 2xLate
FROM
(
SELECT class, studentid, COUNT(*) AS cnt
FROM `laterec-students`
WHERE waived!='Waived'
GROUP BY class, studentid
) t
GROUP BY class;

关于mysql - 使用计数表优化 SQL 查询多重连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11014050/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com