选择计数 = 1

SELECT WHERE COUNT = 1(选择计数 = 1)
本文介绍了选择计数 = 1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

LESSON 具有字段 LessonDate、MemberId (其中只有这两个是相关的)

Table LESSON has fields LessonDate, MemberId (Among others but only these two are relevant)

用英语:给我一份只上过一门课的学生上那门课的日期列表.

In English: Give me a list of the dates on which students that have only ever taken 1 class, took that class.

我已经尝试了很多东西.这是我最近的尝试:

I have tried a number of things. Here's my latest attempt:

SELECT LessonDate 
FROM LESSON 
WHERE (SELECT COUNT(MemberId) GROUP BY (MemberId)) = 1

只是不断返回 SQL 错误.很明显,语法和逻辑都关了.

Just keeps returning SQL errors. Obviously, the syntax and logic are off.

推荐答案

这个查询一开始可能看起来有点违反直觉.您需要按 MemberId 分组以获取只上过一门课的学生:

The query may seem a little counter-intuitive at first. You need to group by MemberId to get the students who only took one class:

select max(l.LessonDate) as LessonDate
from Lesson l
group by l.MemberId
having count(*) = 1;

因为学生只有一堂课,所以 max(l.LessonDate) 就是那个日期.因此,这可以满足您的要求:它会获取只参加过一门课程的成员的所有日期.

Because there is only one class for the student, max(l.LessonDate) is that date. Hence this does what you want: it gets all the dates for members who only took one class.

你的思路也很接近.这是我认为您正在寻找的查询:

Your line of thinking is also pretty close. Here is the query that I think you were looking for:

SELECT LessonDate 
FROM LESSON 
WHERE MemberId in (SELECT l2.MemberId
                   FROM Lesson l2
                   GROUP BY l2.MemberId
                   HAVING COUNT(*) = 1
                  );

如果您想获取具有 2 或 3 行的成员的日期,这种方法更通用.

This approach is more generalizable, if you want to get the dates for members that have 2 or 3 rows.

这篇关于选择计数 = 1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)