Sql server sql server 2008,计数和区分组合在一起
这是我的密码。总共109行 一, 这个代码给了我9行老师的名字 二, 这个密码给了我Sql server sql server 2008,计数和区分组合在一起,sql-server,Sql Server,这是我的密码。总共109行 一, 这个代码给了我9行老师的名字 二, 这个密码给了我 column1 34 问题是如何结合在一起。数一数学生。姓名栏1,教师栏2 我只需要名单和总数。比如, name total_student sam 24 John 35 Julie 34 等等…… 我在数学生时遇到了麻烦。它本身是可以的,但是当我使用DISTINCT和COUNT时,它会给我一个错误 我试过了 SELECT COUNT(studen
column1
34
问题是如何结合在一起。数一数学生。姓名栏1,教师栏2
我只需要名单和总数。比如,
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
不起作用。救命啊 您需要使用
Join
和groupby
。
我不能肯定,除非知道你的表结构和数据库设计,因为这个表似乎有点复杂,因为它需要一个自连接。
你可以在这方面试试
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
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
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