简体   繁体   中英

SQL - count occurrences of gender

I'm new to SQL and I am creating a movie rental site database. I have to show some summary statistics of the database, so I'm planning to show the number of males and females that have selected films of a certain certification to rent.

The output I want is:

Certificate  No. Males  No. Females
-----------  ---------  -----------
U                #           #
PG               #           #
12               #           #
15               #           #
18               #           #

The relevant tables for this query are:

FILM {FID (PK), Film_Title, Certificate, Date_of_Release}
MEMBER {MID (PK), ..., Gender}
LIST {MID (FK), FID (FK)}

FILM and MEMBER table should be quite self-explanatory, while a LIST is a selection of films a MEMBER wishes to rent. It's like a shopping basket, if you like. Each member only has one list and each list can contain many films. I tried to come up with a query but Access wouldn't let me run it:

SELECT Gender, COUNT(*) AS Gender_per_Certificate
FROM (SELECT DISTINCT Film_Title, Certificate, Gender
FROM (SELECT *
FROM Film, Member, List
WHERE Film.FID=List.FID
AND Member.MID=List.MID)
WHERE Film_Title IN (SELECT Film_Title
FROM (SELECT * 
FROM Film, Member, List
WHERE Film.FID=List.FID
AND Member.MID=List.MID)
WHERE Certificate=[Certificate?]
GROUP BY Certificate))
WHERE (((Member.[Gender])="M")) OR ((("F")<>False))
GROUP BY Gender;

The error is

You tried to execute a query that does not include the specified expression 'FID' as part of an aggregate function

I'm not sure what this error means - could someone please explain it? Also, how can I execute the query correctly?

I understand this might be a really simple query that I've overcomplicated, would appreciate any help at all, thanks a lot for your time in advance!

If you use a case statement ( IIF in access, thank you @HansUp) to determine which are male and female, grouping by certificate, you should get your answer.

select
  f.Certificate, 
  sum(IIF(m.[gender] = 'M',1, 0)) as [# of males],
  sum(IIF(m.[gender] = 'F',1, 0)) as [# of females]
from
  (member m 
  inner join list l on m.mid = l.mid)
  inner join film f on l.fid = f.fid
group by f.Certificate

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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