27,579
社区成员
发帖
与我相关
我的任务
分享
CREATE VIEW dbo.view_test
AS
SELECT a.classId
,a.className
,a.roomNo
,a.managerName
,(SELECT COUNT(b.classId) FROM dbo.B_Student AS b WHERE a.classId=b.classId) AS stuCnt
FROM dbo.A_Class AS a
USE tempdb
GO
IF OBJECT_ID('view_test') IS NOT NULL DROP VIEW view_test;
IF OBJECT_ID('A_Class') IS NOT NULL DROP TABLE A_Class;
IF OBJECT_ID('B_Student') IS NOT NULL DROP TABLE B_Student;
GO
CREATE TABLE A_Class(
classId INT PRIMARY KEY
,className NVARCHAR(10)
,roomNo NVARCHAR(10)
,managerName NVARCHAR(10)
)
CREATE TABLE B_Student(
classId INT,
stuName NVARCHAR(10),
gender NCHAR(1),
age INT
)
GO
INSERT INTO A_Class(classId,className,roomNo,managerName) VALUES(1,'一(1)班','301','李小刚')
INSERT INTO A_Class(classId,className,roomNo,managerName) VALUES(2,'一(2)班','302','王芬')
INSERT INTO A_Class(classId,className,roomNo,managerName) VALUES(3,'一(3)班','303','王力宏')
INSERT INTO B_Student(classId,stuName,gender,age) VALUES (1,'小明','男',10)
INSERT INTO B_Student(classId,stuName,gender,age) VALUES (1,'小张','男',10)
INSERT INTO B_Student(classId,stuName,gender,age) VALUES (2,'小华','女',10)
INSERT INTO B_Student(classId,stuName,gender,age) VALUES (2,'小李','女',10)
INSERT INTO B_Student(classId,stuName,gender,age) VALUES (2,'小陈','男',10)
GO
----------- 以上为测试表及测试数据 ----------------------
--创建视图
CREATE VIEW dbo.view_test
AS
SELECT a.classId
,a.className
,a.roomNo
,a.managerName
,COUNT(b.classId) AS stuCnt
FROM dbo.A_Class AS a LEFT JOIN dbo.B_Student AS b ON a.classId=b.classId
GROUP BY a.classId
,a.className
,a.roomNo
,a.managerName
GO
--查询视图
SELECT * FROM view_test
/*
classId className roomNo managerName stuCnt
----------- ---------- ---------- ----------- -----------
1 一(1)班 301 李小刚 2
2 一(2)班 302 王芬 3
3 一(3)班 303 王力宏 0
*/