这是我的代码。它总共109行。
1
SELECT DISTINCT(SELECT top 1 lastname+', '+firstname FROM users WHERE privilege not in
('Counselor','Guardian') AND userindex IN (SELECT userindex FROM studenttouser
WHERE studentindex = students.studentindex)) AS teacher
这段代码给了我9行教师的名字。
2
SELECT COUNT(students.lastname) as total_student
from table
where (SELECT top 1 lastname+', '+firstname FROM users WHERE privilege not in
('Counselor','Guardian') AND userindex IN (SELECT userindex FROM studenttouser
WHERE studentindex = students.studentindex))='sam'
这段代码给了我
column1
34
问题是如何结合在一起。 COUNT students.name-column1,DISTINCT teacher-column2
我只需要名单和总数。例如;
name total_student
sam 24
John 35
Julie 34
等...... 我和计票学生一起遇到了麻烦。它本身就可以,但是当我使用DISTINCT和COUNT时它会给我一个错误。
我试过
SELECT COUNT(students.lastname) as Student_total,
DISTINCT(SELECT top 1 lastname+', '+firstname FROM users
WHERE privilege not in
('Counselor','Guardian') AND userindex IN (SELECT userindex FROM studenttouser
WHERE studentindex = students.studentindex)) AS teacher
不起作用。 HELP !!!
答案 0 :(得分:0)
您需要使用Join
和Group By
。
我不能确定除非知道你的表结构和数据库设计,因为这个表似乎有点复杂,因为它需要自联接。
你可以尝试这些方面的东西。
SELECT Name, total_student
FROM
(
SELECT DISTINCT(SELECT top 1 lastname+', '+firstname as Name
FROM users WHERE privilege not in
('Counselor','Guardian') AND userindex IN (SELECT userindex FROM studenttouser
WHERE studentindex = students.studentindex))
) teacher
INNER JOIN
(
SELECT COUNT(students.lastname) as total_student
from table
) as Student
ON (SELECT top 1 lastname+', '+firstname
FROM users
WHERE privilege not in ('Counselor','Guardian') AND userindex IN (SELECT userindex FROM studenttouser
WHERE studentindex = students.studentindex)
)=teacher.Name
GROUP BY teacher.Name