选择在某一天访问过所有课程的所有成员

时间:2019-12-22 23:42:06

标签: sql postgresql

我正在尝试创建一个查询,以选择所有具有“ GOLD”状态并且还参加了在星期日进行的所有课程的成员。

这是我的选择语句:

SELECT member_ID, first_name, last_name
FROM member
         JOIN person p on member.fk_person = p.person_ID
         JOIN enrolment e on member.member_ID = e.fk_member_ID
         JOIN membership m on member.fk_membership = m.membership_ID
         JOIN class c on e.fk_class_ID = c.class_ID
WHERE status = 'GOLD'
GROUP BY member_ID, first_name, last_name
HAVING COUNT(*) = (SELECT COUNT(*) FROM class WHERE weekday = 'SUNDAY');

以下语句返回两个发生在星期日的类:

SELECT count(class_id)
FROM class
WHERE weekday = 'SUNDAY';

我的选择语句顶部是否错误?我应该怎么做才能实现自己的目标?

此处提供了整个SQL脚本:https://pastebin.com/MtAp2p5k

2 个答案:

答案 0 :(得分:1)

您需要在查询的主要部分中对COUNT进行条件设置,以便它也仅在星期日对课程进行计数:

SELECT member_ID, first_name, last_name
FROM member
         JOIN person p on member.fk_person = p.person_ID
         JOIN enrolment e on member.member_ID = e.fk_member_ID
         JOIN membership m on member.fk_membership = m.membership_ID
         JOIN class c on e.fk_class_ID = c.class_ID
WHERE status = 'GOLD' AND weekday = 'SUNDAY'
GROUP BY member_ID, first_name, last_name
HAVING COUNT(*) = (SELECT COUNT(*) FROM class WHERE weekday = 'SUNDAY');

输出(用于示例数据)

member_id   first_name  last_name
1           Peter       Simmler
2           Frances     Simmler

Demo on dbfiddle

答案 1 :(得分:1)

我相信您只是缺少一个WHERE谓词,该谓词只过滤那些在星期天上课的人(这样count(*)才能正常工作):

import java.util.Scanner;

public class Test {
    public static void main(String[] args) {
        Scanner scan=new Scanner(System.in);

        //raza of type integer
        //nume of type String
        System.out.print("Dimension is = " );
        // The replaceAll("[^\\d]+", "") removes all characters that aren't digits
        int n=Integer.parseInt(scan.nextLine().replaceAll("[^\\d]+", ""));
        // Arrays of objects are declared like this:
        Cerc[] c = new Cerc[n]; //array of objects

        //init array
        for (int i = 0; i <c.length ; i++) {
            c[i]=new Cerc();

            System.out.print("Raza=");
            // The replaceAll("[^\\d]+", "") removes all characters that aren't digits
            c[i].raza = Integer.parseInt(scan.nextLine().replaceAll("[^\\d]+", ""));
            System.out.print("Nume=");
            c[i].nume = scan.nextLine();
        }
        //Printing array
        for (int i = 0; i <n ; i++) {
            c[i].afisare(); 
        }
    }
}