Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/27.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server sql server 2008,计数和区分组合在一起_Sql Server - Fatal编程技术网

Sql server sql server 2008,计数和区分组合在一起

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

这是我的密码。总共109行

一,

这个代码给了我9行老师的名字

二,

这个密码给了我

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