如何在SQL中实现此算法?

Jon*_*Jon 1 sql sybase

我试图在SQL(transact sql)中实现一个算法,并且鉴于我目前的能力,发现它很困难.我试图将问题排除在问题之外.这个算法背后的基本思想是用户计划一个月的预算.他们很清楚金钱来来往往多少钱.现在是月中.问题是:根据目前的义务,在本月剩余时间里,账户的最差位置是什么?

例如,看看下面的时间线吧

Today = 15th
Util  = 17th
B-day = 19th
Cable = 22nd
Wages = 25th
Run Code Online (Sandbox Code Playgroud)

在17日,该帐户将比今天少150美元.在19号,帐户将比今天多100美元.在22日,该帐户将比今天少25美元.在25日,该帐户将比今天多975美元.

所以在这个例子中,查询将返回 - $ 150.

注意:我只关心返回的负值.如果它是否定的,则表示您有义务,不应该花费该金额.如果是积极的,那也没关系.您还不能在帐户中花钱.

|                                   |                                             |
|          ^            ^           |    ^            ^                           |
|          |Rent(-500)  |Phone(-50) |    |Util(-150)  |Cable(-125)                |
-----------------------------------------------------------------------------------
|        ^                          |       ^                     ^               |
|        |Wages(+1000)              |       |B-day(+250)          |Wages(+1000)   |
|                                   |                                             |
Past                                Today                                         Future
Run Code Online (Sandbox Code Playgroud)

我们可以用于此问题的简单表:

create table MoneyFlow
(
    fiscalEventID int not null, 
    value money,
    transactionDate date
)
Run Code Online (Sandbox Code Playgroud)

还有一种看待它的方法.你如何在SQL中执行以下算法?

Algorithm
  Input:  Start date, End date
  Output: Worst position the account is going to be in in the future.

  WorstPosition = 0 //only want worst position if it is negative.
  For each date D between start date and end date where a transaction takes place
     Position_D = Sum deposits and withdrawls between start date and D
         If Position_D < WorstPosition
     WorstPosition =  Position_D 

  return WorstPosition 
Run Code Online (Sandbox Code Playgroud)



还有一点请注意我使用的数据库是Sybase

如果您需要澄清任何细节,请与我们联系.谢谢!

Jul*_*iet 5

在我看来,你正在尝试创建一个运行总计,然后从运行总计中选择最小的运行值.

以下不是很好,但它避免了游标.

从以下内容开始填充表格:

CREATE TABLE #temp
    (someDate datetime
    ,amount decimal)

INSERT INTO #temp (someDate, amount)
SELECT '2009-01-01', 1000 UNION ALL
SELECT '2009-01-02', -500 UNION ALL
SELECT '2009-01-03', -50 UNION ALL
SELECT '2009-01-04', -150 UNION ALL
SELECT '2009-01-05', 250 UNION ALL
SELECT '2009-01-06', -125 UNION ALL
SELECT '2009-01-07', 1000
Run Code Online (Sandbox Code Playgroud)

这是一个简单的查询,以获得最小运行总数:

SELECT
    TOP 1
    base.someDate
    ,runningTotal =
        (SELECT sum(derived.amount)
        FROM #temp derived
        WHERE derived.someDate <= base.someDate)
FROM #temp base
ORDER BY runningTotal ASC
Run Code Online (Sandbox Code Playgroud)