使用其他值计算值

时间:2012-11-26 13:02:58

标签: sql sql-server sql-server-2008

让我们简单一点:

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的新手,也许这很简单,我应该知道如何制作它,但我没有,我需要帮助。

3 个答案:

答案 0 :(得分: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 FIDDLE EXAMPLE

答案 1 :(得分:0)

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

答案 2 :(得分: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 Fiddle

相关问题