具有聚合函数的嵌套查询Slick

时间:2017-11-14 10:05:30

标签: sql scala slick nested-query

我正在使用Slick构建一些SQL查询。我有一些嵌套查询的查询,我无法弄清楚如何将这一切合并为一个。

我的SQL查询:

select count(*) from (

    select TOP 1 WITH TIES sum(c) cc, c1, c2 from (

    SELECT count(*) c, town_from c1, town_to c2 from trip
    where town_from>=town_to
    group by town_from, town_to
    union all
    SELECT count(*) c,town_to, town_from from trip
    where town_to>town_from
    group by town_from, town_to
    ) as t

    group by c1,c2
    order by cc desc

    ) as tt

我使用Slick完成此查询的未完成版本:

val subquery1 = TripTable.table.filter(t => t.townFrom >= t.townTo)
      .groupBy(t => (t.townFrom, t.townTo))
      .map{ case ((townFrom, townTo), group) => (group.length ,townFrom, townTo)}
val subquery2 = TripTable.table.filter(t => t.townTo > t.townFrom)
      .groupBy(t => (t.townFrom, t.townTo))
      .map{ case ((townFrom, townTo), group) => (group.length ,townFrom, townTo)}

    val t = subquery1 union subquery2
val tt = t.map{ case subquery1 => (subquery1._1, subquery1._2, subquery1._3) }
              .groupBy{case (sub1, sub2, sub3) => (sub2, sub3)}
                  .map{ case ((sub1,sub2, sub3), group) => (group.map(_._1).sum.get, sub2, sub3)}
                      .sortBy{ case (sum, sub2, sub3) => sum}
                        .take(1)
db.run(tt.length.result)

我会非常感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

此查询对我有用:

val subquery1 = TripTable.table.filter(t => t.townFrom >= t.townTo)
      .groupBy(t => (t.townFrom, t.townTo))
        .map{ case ((townFrom, townTo), group) => (group.length, townFrom, townTo)}

    val subquery2 = TripTable.table.filter(t => t.townTo > t.townFrom)
      .groupBy(t => (t.townFrom, t.townTo))
        .map{ case ((townFrom, townTo), group) => (group.length, townFrom, townTo)}

    val t = subquery1 union subquery2
    val tt = t.map { case subquery1 => (subquery1._1, subquery1._2, subquery1._3) }
      .groupBy { case (sub1, sub2, sub3) => (sub2, sub3) }
      .map { case ((sub2, sub3), group) => (group.map(_._1).sum, sub2, sub3) }
      .sortBy { case (sum, sub2, sub3) => sum }
                            .take(1)
    println(tt.length.result.statements)