正确使用CTE的方法

时间:2018-01-26 14:01:58

标签: sql common-table-expression

我是Common Table Expressions的新手,我想我需要使用一个才能达到我的要求。

如果我运行以下脚本 -

select MainRentAccountReference,EffectiveFromDate,CollectionDay,NumberOfCollections,DirectDebitTotalOverrideAmount 
from DirectDebitApportionment
where id = 1

它会给我以下结果 - enter image description here

因此,对于每个唯一的MainRentAccountReference,我的CTE将返回的每一行 - 我想根据以下条件创建一行。

3行,因为NumberOfCollections设置为3 每行的下列日期 - 01/05 / 18,01 / 06 / 18,01 / 07/18所以基本上加上一个月。 然而,CollectionDate设置为10,那么我希望3个日期是10/05 / 18,10 / 06 / 18,10 / 07/18 最后每行的DirectDebitTotalOverrideAmount值除以NumberOfCollections的数量。

我一直在玩这个并且在我想要实现的结果附近找不到。任何帮助将不胜感激。感谢

2 个答案:

答案 0 :(得分:1)

您可以使用递归CTE

执行此操作
with t as (
      select *
      from DirectDebitApportionment
      where id = 1
     ),
     cte as (
      select . . ., , 1 as collection, DirectDebitTotalOverrideAmount / NumberOfCollections as collection_amount
      from t
      union all
      select . . ., , collection + 1, DirectDebitTotalOverrideAmount / NumberOfCollections as collection_amount
      from cte
      where collection < NumberOfCollections
     )
select . . .
from cte;

在SQL的某些方言中,您需要recursive关键字。

此外,这也可以使用numbers表来完成 - 这比递归CTE更有效(尽管递归CTE通常表现得非常好)。

答案 1 :(得分:0)

这似乎是基于戈登给我的指示 -

class GroupingOperations: NSObject {

var expenses = [Expense]()
var expensePerCollection = [Expense]()

public func getExpenses(collection: String, completionHandler: @escaping([[Expense]], [String]) -> Void){
    self.expenses = CoreDataHelper.retrieveExpenses()//.sorted(by: { $0.modificationDate as! Date > $1.modificationDate as! Date})
    for eachExpense in expenses{
        if eachExpense.collection == collection{
            expensePerCollection.append(eachExpense)
        }
    }

    for eachCollectionExpense in expensePerCollection{
        print("Name: \(String(describing: eachCollectionExpense.name)) - Date: \(String(describing: eachCollectionExpense.modificationDate))")
    }
    let sortedExpensePerCollection = expensePerCollection.sorted(by: { $0.modificationDate as! Date > $1.modificationDate as! Date})
    var groupedExpenses = Dictionary(grouping: sortedExpensePerCollection, by: {($0.modificationDate! as Date).convertToJSONDate()})

    let keys = Array(groupedExpenses.keys)
    var items:[[Expense]] = []
    let groupedExpensesSorted = groupedExpenses.sorted(by: {$0.0 < $1.0})
    for eachKey in keys {
        items.append(groupedExpensesSorted[eachKey])
    }
    completionHandler(items, keys)
    //let sortedKeys = keys.sorted(by: {$0 > $1})
}
}

给我以下结果 -

enter image description here