1

让我们简单点:

USE Example1

    CREATE TABLE Person
    (PersonID int PRIMARY KEY IDENTITY(1,1),
    FirstName nchar(20) NOT NULL,
    LastName  nchar(20) NOT NULL,
    Salary money NOT NULL
    ) 

        CREATE TABLE Student
        (StudentID int PRIMARY KEY IDENTITY(1,1),
        FirstName nchar(20) NOT NULL,
        LastName  nchar(20) NOT NULL,
        FatherID int NOT NULL,
        MotherID int NOT NULL,
        CONSTRAINT fk_Student_FatherID FOREIGN KEY (FatherID)
        REFERENCES Person(PersonID),
        CONSTRAINT fk_Student_MotherID FOREIGN KEY (MotherID)
        REFERENCES Person(PersonID)
        ) 

    CREATE TABLE Registration
    (RegistrationID int PRIMARY KEY IDENTITY(1,1),
    StudentID int NOT NULL,
    Date datetime NOT NULL,
    MonthlyPayment ??????????
    CONSTRAINT fk_Registration_StudentID FOREIGN KEY (StudentID)
    REFERENCES Student(StudentID)
    ) 

    INSERT INTO Person VALUES ('John','Doe','1000')
    INSERT INTO Person VALUES ('Mary','Poppins','800')

    INSERT INTO Student VALUES ('Gary','Doe', 1, 2)

    INSERT INTO Registration VALUES (1, getdate(),???)

我有一个学生要在学校进行注册,并且每月支付一笔款项,FatherSalary*0.5 + MotherSalary*0.5但我不知道如何做到这一点。我是 SQL 新手,也许这很简单,我应该知道如何制作它,但我不知道,我需要帮助。

4

3 回答 3

4

你确定你MonthlyPayment的表中需要列吗?

您可以创建Registration没有MonthlyPayment字段的表,然后创建一个视图

create view vw_Registration
as
    select
        R.RegistrationID,
        R.StudentID,
        R.Date,
        F.Salary * 0.5 + M.Salary * 0.5 as MonthlyPayment
    from Registration as R
        left outer join Student as S on S.StudentID = R.StudentID
        left outer join Person as F on F.PersonID = S.FatherID
        left outer join Person as M on M.PersonID = S.MotherId

SQL 提琴示例

于 2012-11-26T13:09:15.767 回答
0

第一手的观点听起来不错,但我可以想象一个场景,您想根据某个时间点的可用数据计算每月付款,因此每次父亲或母亲的工资发生变化时,每月付款都不会改变...

在这种情况下,您可以使用:

INSERT INTO Registration 
(StudentID, Date, MonthlyPayment)
SELECT S.StudentID, getdate(), ISNULL(F.Salary, 0) * 0.5 + ISNULL(M.Salary, 0) * 0.5
FROM Student as S
left outer join Person as F on F.PersonID = S.FatherID
left outer join Person as M on M.PersonID = S.MotherId
WHERE S.StudentID = 1

SQL小提琴

于 2012-11-26T13:41:51.040 回答
0

如果表达式“FatherSalary*0.5 + MotherSalary*0.5”不会改变,那么我想你可以使用触发器。你的触发器将检查插入到你的注册表。在插入时,它将获取学生 ID,然后使用此 ID 从您的学生表和您的个人表中获取必要的数据。那时,您将可以访问父亲和母亲的 Money 列。计算结果,并让触发器为您插入。

于 2012-11-26T13:14:13.463 回答