我想根据指定的批次计算学生的ID。学生ID位于其他表中。我正在尝试的是从包含batchid的dbo.Batches中获取所有批次的详细信息。与此同时,我想计算在该批次中注册的学生人数。 studentid和批处理ID在dbo.studentbatchrelation表中。我到目前为止所尝试的是,应用子查询来生成批次的详细信息以及在特定批次中注册的学生数量。
以下是我的询问:
查询
(Select
Count(studentId) as TotalStudents
from
dbo.StudentBatchRelation
where
BatchId in (Select
b.Id as BatchId, b.CourseId as CourseId,
b.BatchNumber as BatchNumber,
b.BatchTimingsFrom as BatchTimingsFrom,
b.BatchTimingsTo as BatchTimingsTo,
b.BatchDuration as Duration, b.BatchDate as BatchDate,
b."Days" as "Days", b.CourseRoomId as CourseRoomId,
c.CourseName as CourseName,
cr.RoomName as RoomName,
cr.RoomCapacity as RoomCapacity
from
dbo."Batches" b, dbo.Courses c,
dbo.CourseRooms cr
where
b.CourseId = c.Id
and b.CourseRoomId = cr.Id
and b.ActiveBatch = 1 ));
批次的表格结构
CREATE TABLE [dbo].[Batches] (
[Id] VARCHAR (250) NOT NULL,
[CourseId] VARCHAR (250) NOT NULL,
[BatchNumber] VARCHAR (250) NOT NULL,
[BatchTimingsFrom] TIME (7) NOT NULL,
[BatchTimingsTo] TIME (7) NOT NULL,
[BatchDuration] VARCHAR (50) NOT NULL,
[Days] VARCHAR (250) NOT NULL,
[CourseRoomId] VARCHAR (250) NOT NULL,
[BatchDate] VARCHAR (250) NULL,
[ActiveBatch] BIT DEFAULT ((0)) NULL,
CONSTRAINT [PK_Batches] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_BATCHES_COURSE] FOREIGN KEY ([CourseId]) REFERENCES [dbo].[Courses] ([Id]) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT [FK_BATCHES_CourseRoom] FOREIGN KEY ([CourseRoomId]) REFERENCES [dbo].[CourseRooms] ([Id]) ON DELETE CASCADE ON UPDATE CASCADE
);
StudentBatchRelation的表格结构
CREATE TABLE [dbo].[StudentBatchRelation] (
[Id] VARCHAR (250) NOT NULL,
[BatchId] VARCHAR (250) NOT NULL,
[StudentId] VARCHAR (250) NOT NULL,
[TransactionId] VARCHAR (250) NULL,
[RemainingAmount] VARCHAR (250) NULL,
[Status] VARCHAR (250) NULL,
CONSTRAINT [PK_StudentBatchRelation] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_StudentBatchRelation_Batch] FOREIGN KEY ([BatchId]) REFERENCES [dbo].[Batches] ([Id]) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT [FK_StudentBatch_TransactionId] FOREIGN KEY ([TransactionId]) REFERENCES [dbo].[TransactionTable] ([Id]) ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT [FK_StudentBatchRelation_Student] FOREIGN KEY ([StudentId]) REFERENCES [dbo].[User] ([Id])
);
答案 0 :(得分:1)
我最好使用join
;
Select
SBR.BatchId, Count(SBR.StudentId) as TotalStudents
from
dbo.StudentBatchRelation SBR
inner join Batches B ON SBR.BatchId = B.Id
inner join Courses C ON C.Id = B.CourseId
inner join CourseRooms CR ON CR.Id = B.CourseRoomId
where B.ActiveBatch = 1
group by SBR.BatchId
答案 1 :(得分:0)
SFSafariViewController