如何在Microsoft Cosmos Scope中编写循环以逐行处理?

时间:2017-12-18 19:21:21

标签: c# u-sql cross-join cosmos

更新:我想要做的一个例子:

现有表格:

1st Table name: DistinctAcctDay;
Column name: ID int, AccountingDate datetime;
Values: (1, 2017/05/01);
     (2, 2017/08/01);
     (3, 2017/09/01);


2nd Table name: TransferOut;
Column name: AccountingDate datetime; Amount decimal;
Values: (2017/01/01, 10);
(2017/02/01, 13);
(2017/06/25, 15);
(2017/08/03, 18);
(2017/08/08, 30);

我想让Cosmos脚本返回3以下(或n,取决于第1个表中存在多少行)输出当天之前所有历史数据的总和:

1)第1表中2017/05/01之前的第2表中的金额:数字应为23;

2)第一张表中2017/08/01之前的第二张表中的金额:数字应为10 + 13 + 15 = 38;

3)第1表中2017/09/01之前的第2表中的金额:数字应为10 + 13 + 15 + 18 + 30 = 86;

脚本应该用Cosmos编写。

提前感谢每个人的帮助。

/////////////////////////

我的想法:

我想在第一个循环并每次选择一行(一个日期)并使用该日期作为从第二个表中导出数据的标准。

如果用sql编写,它可能如下所示。

Declare @Counter int,@MaxRowLimit int; 
Set @Counter =1;
Set @MaxRowLimit = (SELECT COUNT(*) FROM DistinctAcctDay);
WHILE @Counter <= @MaxRowLimit
BEGIN
  PickAcctDay=
  SELECT AccountingDay
  FROM DistinctAcctDayId
  WHERE ID =@Counter;

  TransferOut =
     SELECT SUM(Amount) FROM TransferOut
     WHERE AccountingDate <= PickAcctDay;   
   SET @Counter =@Counter +1
END

然而,它需要用USQL编写,我不熟悉USQL,也不熟悉C#。我写了下面的内容(这是不正确的)并且我被卡住了......

int counter=1; int MaxRowLimit;
for (counter = 1; counter <= MaxRowLimit; counter++)
{
  DateTime PickAcctDay =
  SELECT AccountingDay
  FROM DistinctAcctDayId
  WHERE ID ==@Counter;

  TransferOut =
     SELECT SUM(Amount) FROM TransferOut
     WHERE AccountingDate <= PickAcctDay;
}

1 个答案:

答案 0 :(得分:1)

@DistinctAcctDay = 
SELECT * FROM 
    ( VALUES
    (1, new DateTime(2017,05,01)),
    (2, new DateTime(2017,08,01)),
    (3, new DateTime(2017,09,01))
    ) AS T(Id, AccountingDate);


@TransferOut = 
SELECT * FROM 
    ( VALUES
    (new DateTime(2017,01,01), 10),
    (new DateTime(2017,02,01), 13),
    (new DateTime(2017,06,25), 15),
    (new DateTime(2017,08,03), 18),
    (new DateTime(2017,08,08), 30)
    ) AS T(AccountingDate, Amount);

@result = 
       SELECT d.Id, SUM(Amount) AS sumAmount
       FROM  @DistinctAcctDay AS d
       CROSS JOIN @TransferOut AS t
       WHERE d.AccountingDate >= t.AccountingDate 
      // WHERE d.AccountingDate BETWEEN t.AccountingDate AND d.AccountingDate
       GROUP BY d.Id;