如何在日期之间获取行值?

时间:2016-04-18 11:08:32

标签: sql asp.net-mvc-5 sql-server-2014

我有一个存储过程,可以在MinDate和MaxDate之间获取一行。

ALTER PROCEDURE [dbo].[GetFilteredDomainDetails]
    @Id bigint,
    @From datetime2,
    @To datetime2
AS
BEGIN
    SET NOCOUNT ON;

    SELECT 
        DomainId, [Date], DomainName, 
        ServerPerformance, DatabasePerformance, SoldTickets 
    FROM 
        DomainDetailDataHistory
    WHERE 
        DomainId = @Id AND Date >= @From AND date <=@To
    ORDER BY 
        date ASC
END

问题是我在计算行之间的售票数量:

    for (int i = databaseData.Count() - 1; i > 0; i--)
    {
        long soldtickets = databaseData[i].SoldTickets - databaseData[i - 1].SoldTickets;
        databaseData[i].SoldTickets = soldtickets < 0 ? databaseData[i].SoldTickets : soldtickets;
    }

问题:

我的是,为了获得正确的票证计算,我需要一个额外的行,但是要低估。

我可以这样做:

SELECT TOP 1  
    DomainId, [Date], DomainName, 
    ServerPerformance, DatabasePerformance, SoldTickets 
FROM
    DomainDetailDataHistory 
WHERE 
    [Date] > @From AND DomainId = @Id   
ORDER BY 
    date ASC

并在服务器上将其作为辅助选择语句接收。

但是我觉得这不是一个干净的方式来完成我正在寻找的东西,我很好奇,如果有更好的方法?

2 个答案:

答案 0 :(得分:0)

我正在寻找可以在一个选择的陈述中得到我的东西,但意识到这只是耗费时间来解决它,所以我发泄以下解决方案:

DECLARE @Temp TABLE(DomainId  bigint,[Date] datetime2,DomainName varchar(max), ServerPerformance bigint, DatabasePerformance bigint, SoldTickets bigint )

INSERT INTO @Temp
            SELECT TOP 1 DomainId, [Date],DomainName, ServerPerformance, DatabasePerformance, SoldTickets FROM DomainDetailDataHistory
            WHERE DomainId = @Id AND Date < @From 
            order by date DESC

SELECT * FROM @Temp

SELECT h.DomainId, h.[Date], h.DomainName, h.ServerPerformance, h.DatabasePerformance, h.SoldTickets 
FROM DomainDetailDataHistory h
JOIN @Temp T ON T.DomainId = h.DomainId
WHERE h.DomainId = @Id AND h.[Date] >= T.[Date] AND h.[date] <=@To
order by date asc

答案 1 :(得分:-1)

您可以像这样修改代码,以便更好地执行SELECT DomainId, [Date],DomainName, ServerPerformance, DatabasePerformance, SoldTickets FROM DomainDetailDataHistory WHERE DomainId = @Id AND Date between @From AND @To order by date asc