如何计算SQL表中的ROWS数量

时间:2016-07-11 11:25:55

标签: sql asp.net sql-server

我有两张桌子。第一个表(Class)是表,其中有学生可以选择的类,最后一列(numberOfRegistration)是每个类的注册数。这是第一张表:

idClass int;
name varchar(50);
date varchar(50);
state bit;
description nvarchar(50);
numberOfRegistration  int

第二张表(注册)用于注册:

idRegistration  int;
dateOfRegistration  date;
name varchar(50);
lastName varchar(50);
city nvarchar(50);
adress nvarchar(50);
postalNumber int;
idClass int - this is foreign key, references idClass from Class table ;

有没有人知道如何在表注册中获取每个类的注册数,并将该数据写入表Class中的最后一列(numberOfRegistration)。

谢谢

4 个答案:

答案 0 :(得分:1)

试试这个:

if ([SFSafariViewController class] != nil) {
        SFSafariViewController *sfvc = [[SFSafariViewController alloc] initWithURL:URL];
        sfvc.delegate = self;
        [self presentViewController:sfvc animated:YES completion:nil];
    } else {
        if (![[UIApplication sharedApplication] openURL:URL]) {
            //NSLog(@"%@%@",@"Failed to open url:",[URL description]);
        }
    }

答案 1 :(得分:0)

您可以使用派生表将组结果与类表组合,如下所示:

SELECT name, NumberOfRegistrations
FROM Class 
LEFT JOIN 
(
    SELECT idClass, count(*), NumberOfRegistrations 
    FROM Registration 
    GROUP BY idClass
) D ON class.idClass = D .idClass 

答案 2 :(得分:0)

您可以考虑构建完整解决方案的两个步骤。 第一步是使用当前值作为起点更新Class表。 第二步,您可以创建一个SQL触发器,以使相关类的注册计数保持最新

这是第一步的更新脚本<​​/ p>

update class 
set numberOfRegistration = cnt
from class c 
left join (
    select r.idClass, COUNT(r.idRegistration) cnt
    from class c
    left join Registration r on c.idClass = r.idClass
    group by r.idClass
) t on c.idClass = t.idClass

这是SQL触发器代码。我创建了sample SQL trigger作为After Insert,Update,Delete触发器,如下面的代码所示

Create TRIGGER dbo.Registration_changes
 ON dbo.Registration
AFTER INSERT, UPDATE, DELETE
AS

WITH CTE AS (
    select idClass from inserted
    union all
    select idClass from deleted
), cte2 as (
    select CTE.idClass, COUNT(r.idRegistration) cnt
    from cte 
    left join Registration r on CTE.idClass = r.idClass
    Group By CTE.idClass
)
update Class
set numberOfRegistration = cte2.cnt
from cte2 
where class.idClass = cte2.idClass

GO 

我希望它有所帮助,

答案 3 :(得分:-1)

您可以使用以下查询:

select idClass, count(*) as [NumberOfRegitsration PerClass] 
from Registration 
group by idClass