I'me needing some help with a query on a non-profit project I'm involved
with. I appreciate any help.
It's a system to keep track of incidents in schools, including drug
offenses. Each incident can have zero or more drug incidents related with
it, and each of these incidents can have 1 or more drugs involved. To
complicate things a bit, I need a query that will return these incidents
by different drugs and grades.
What I need is to find a count of drug incidents grouped by drugs and
grade. Here's the table stucture (summarized):
create table sds_grades (
constraint sds_grades_pk primary key,
create table sds_offenders (
constraint sds_offenders_pk primary key,
constraint sds_offenders_part_id_fk references sds_participants,
constraint sds_offenders_incident_id_fk references sds_incidents on delete cascade,
constraint sds_offenders_grade_id_fk references sds_grades,
create table sds_drugs (
constraint sds_drugs_pk primary key,
create table sds_drug_offenses (
constraint sds_drug_offenses_pk primary key,
offender_id integer constraint sds_drug_offender_id_fk references sds_offenders on delete cascade,
constraint sds_drug_id_fk references sds_drugs,
constraint sds_drug_violation_id_fk references sds_drug_violations,
The query I came up with so far was this:
SELECT COUNT(incident_id), drug_name, grade_name
FROM sds_offenders o, sds_drugs d, sds_drug_offenses do, sds_grades g
WHERE o.drug_p = 't'
AND o.offender_id = do.offender_id
AND d.drug_id = do.drug_id
GROUP BY drug_name, grade_name, d.sort_key
ORDER BY d.sort_key
This gives me wrong results (if there's one incident in a certain grade,
it'll show the same result for all grades, even though the other grades
have no incidents). It's a work in progress just to give you an idea.
I'm thinking I need an OUTER JOIN somewhere there, but my attempts have
not been successful.
Thanks in advance.