通过嵌套查询参数进行排序

时间:2017-08-17 03:23:36

标签: mysql scala slick-3.0

我试图将以下SQL请求应用于Slick,但随后在实现上被阻止(以下代码是原始问题的转置用例)。

select t1.worker_id,
time_tracked_by_worker_sum,
sum(time_tracked) as time_tracked_sum,
t1.area_id
from tracker as t1
left join
    (
    select worker_id as wid,
    sum(time_tracked) as time_tracked_by_worker_sum,
    from tracker
    where date = '2017-03-20'
    group by worker_id
    ) as t2 on (t1.worker_id = t2.wid)
where date = '2017-03-20'
group by worker_id, area_id
order by time_tracked_by_worker_sum desc, time_tracked_sum desc
limit 100

然后我起草这个版本:

val q1 = for {
  details <- trackerRecords.filter(_.date = '2017-03-20').groupBy(_.workerId).map(r => (r._1, r._2.map(_.timeTracked).sum))
  query <- trackerRecords.filter(_.date = '2017-03-20') if (query.workerId === details._1)
} yield (query, details)

val q2 = q1.sortBy(s => s._2._2) // time_tracked_sum sort is missing
val q3 = q2.groupBy(x => (x._1.workerId, x._1.areaId))
val q4 = q3.map{
  case (key, record) =>
    (record.map(_._1.worker_id),
    key._1,
    // time_tracked_sum sort is missing
    record.map(_._1.timeTracked).sum,
    record.map(_._1.areaId))
} 

我的一个问题是我无法从嵌套查询中添加排序,在我当前的实现中,我无法同时应用time_tracked_by_worker_sum和time_tracked_sum。

我遇到的另一个问题是映射我的字段,由于我的分组,我得到 找不到匹配的形状 错误。

仅供参考,这是trackerRecords表查询。

/**
 * TrackerRecord
 */
trait TrackerRecordTable  {

  this: Profile =>
  import profile.api._
  import jodaSupport._

  class TrackerRecords(tag: Tag) extends Table[TrackerRecord](tag, "tracker") {
    def workerId            = column[WorkerId]("worker_id", O.SqlType("INT"))
    def areaId              = column[AreaId]("area_id", O.SqlType("INT"))
    def timeTracked         = column[Hour]("time_tracked", O.SqlType("INT"))
    def date                = column[LocalDate]("date", O.SqlType("DATE"))
  }

  def trackerRecords = TableQuery[TrackerRecords]
}

感谢您的帮助!

0 个答案:

没有答案