ive been struggling with this for a while:
ive got 2 tables publishers, and students.
im trying to write a query to count how many students share the postccode or "pcode" text value. the data im using has leading leading spaces both before and after, and im meant to take care of that in query as well. another problem is that a few publishers have the same postcode once you trim those spaces from either side, so i need to count the unique trimmed publisher postcodes that are equal to trimmed student postcodes.
im getting some sort of syntax error for a closed bracket on the first line when trying the following and im really stumped
aside from the syntax error im not so certain this will work either
SELECT COUNT(DISTINCT(LTRIM(RTRIM(publishers.pcode)))) As pubpcode
FROM publishers, students
WHERE (LTRIM(RTRIM((publishers.pcode))))) = pubpcode;
SELECT ltrim(rtrim(pubcode)),count(*) Number_of_Student
FROM publisher p inner join students s
on ltrim(rtrim(s.pcode))=ltrim(rtrim(pubcode))
group by ltrim(rtrim(pubcode));
If you want to count unique students for each pubcode then use distinct
SELECT ltrim(rtrim(pubcode)),count(distinct s.id) Number_of_Student
FROM publisher p inner join students s
on ltrim(rtrim(s.pcode))=ltrim(rtrim(pubcode))
group by ltrim(rtrim(pubcode));
I would suggest doing union all
and then aggregating:
select trim(pcode), sum(is_student), sum(is_pub)
from (select pcode, 1 as is_student, 1 as is_pub
from students
union all
select pcode, 0, 1
from publisher
) sp
group by trim(pcode)
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.