如何根据sql server

时间:2015-11-19 07:58:28

标签: sql-server

我的SQL Server存在问题,我的专栏必须根据todays_date和end_date之间的差异来计算remaining_days。然后我希望它计算多少个月,然后金额__ththly应该计算我每个月有多少钱。

示例:

table

我在excel中做了这个,只是为了让你了解我的想法。

1 个答案:

答案 0 :(得分:0)

我想通了,所以这是我的平衡表:

CREATE TABLE [dbo].[Balance] (
[Id]             INT             IDENTITY (1, 1) NOT NULL,
[Balance]        DECIMAL (18, 2) NOT NULL,
[Today_Date]     AS              (CONVERT([char](10),getdate(),(126))),
[Date_end]       DATE            NOT NULL,
[Remaining_Days] AS              (datediff(day,CONVERT([char](10),getdate(),(126)),[Date_end])),
[In_Months]      AS              (datediff(day,CONVERT([char](10),getdate(),(126)),[Date_end])/(30)),
[Amount_Monthly] AS              (CONVERT([decimal](18,2),case when datediff(day,CONVERT([char](10),getdate(),(126)),[Date_end])/(30)=(0) then NULL else [Balance]/(datediff(day,CONVERT([char](10),getdate(),(126)),[Date_end])/(30)) end)),
PRIMARY KEY CLUSTERED ([Id] ASC)

);

以下是我们用于将一些数据插入的月份表:

CREATE TABLE [dbo].[Months] (
[Id]              INT             IDENTITY (1, 1) NOT NULL,
[Month]           VARCHAR (15)    NULL,
[Balance_monthly] DECIMAL (18, 2) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);

以下是Balance表上的触发器,这将根据您有多少个月为您计算。

CREATE TRIGGER [Balance_monthly]
ON [dbo].[Balance]
FOR INSERT, UPDATE
AS
BEGIN
    SET NOCOUNT ON

    UPDATE Months
    SET Months.Balance_monthly = 
    ((Balance.In_Months + 12 - Months.Id) / 12) * Amount_Monthly          
    FROM Balance
    CROSS JOIN Months;

END