【问题标题】:Scala Slick: Getting number of fields with a specific value in a group by queryScala Slick:通过查询获取组中具有特定值的字段数
【发布时间】:2018-11-04 04:56:26
【问题描述】:

我有一张这样的桌子:

|``````````````````````````|
|imgId, pageId, isAnnotated|
|1,      1,       true     |
|2,      1,       false    |
|3,      2,       true     |
|4,      1,       false    |
|5,      3,       false    |
|6,      2,       true     |
|7,      3,       true     |
|8,      3,       true     |
|__________________________|

我想要的结果是:

|`````````````````````````````````````|
|pageId, imageCount, noOfAnotatedImage|
|   1          3          1           |
|   2          2          2           |
|   3          3          2           |
|_____________________________________|

我希望将基于数字字段的注释图像数量设置为 true。

我试过的 Slick 相关代码触发了异常:

  def get = {
    val q = (for {
      c <- WebImage.webimage
    } yield (c.pageUrl, c.lastAccess, c.isAnnotated)).groupBy(a => (a._1, a._3)).map{
      case(a,b) => (a._1, b.map(_._2).max, b.filter(_._3 === true).length, b.length)
    }
    db.run(q.result)
  }

例外:

[SlickTreeException: Cannot convert node to SQL Comprehension
| Path s6._2 : Vector[t2<{s3: String', s4: Long', s5: Boolean'}>]
]

注意:这个Count the total records containing specific values 线程明确表明,在普通 SQL 中,我需要的东西是可能的。

SELECT
   Type
  ,sum(case Authorization when 'Accepted' then 1 else 0 end) Accepted
  ,sum(case Authorization when 'Denied' then 1 else 0 end) Denied
 from MyTable
 where Type = 'RAID'
 group by Type

改了代码还是出现异常:

Execution exception
[SlickException: No type for symbol s2 found for Ref s2]

In /home/ravinder/IdeaProjects/structurer/app/scrapper/Datastore.scala:60
56  def get = {
57    val q = (for {
58      c <- WebImage.webimage
59    } yield (c.pageUrl, c.lastAccess, c.isAnnotated)).groupBy(a => (a._1, a._3)).map{
[60]      case(a,b) => (a._1, b.map(_._2).max, b.map(a => if (a._3.result == true) 1 else 0 ).sum, b.length)
61    }
62    db.run(q.result)
63  }
64

【问题讨论】:

  • 为什么要标记 SQL?
  • 为什么在这里使用 SQL?
  • 因为一天结束时 Slick 将创建 SQL,并且给定的异常也指的是
  • 我想在这里争论是没有意义的。如果Gordon Linoff 说这与 SQL 无关,那么它肯定与 SQL 无关。这太花哨了,有太多层的宏和语法糖,SQL 知识在这里几乎没有用处。
  • 对不起,我忘了看到@GordonLinoff 的声誉,最初我不确定这样的事情是否可以在普通 SQL 中实现

标签: scala slick


【解决方案1】:

根据您的要求,您应该只按pageUrl 分组,以便对同一页面的所有行执行聚合。您可以使用max 聚合lastAccess,并使用sum 在条件Case.If-Then-Else 上使用isAnnotated。 Slick 查询应如下所示:

val q = (for {
    c <- WebImage.webimage
  } yield (c.pageUrl, c.lastAccess, c.isAnnotated)).
  groupBy( _._1 ).map{ case (url, grp) =>
    val lastAcc = grp.map( _._2 ).max
    val annoCnt = grp.map( _._3 ).map(
        anno => Case.If(anno === true).Then(1).Else(0)
      ).sum
    (url, lastAcc, annoCnt, , grp.length)
  }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-15
    • 2019-04-14
    • 1970-01-01
    • 2012-10-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-08
    相关资源
    最近更新 更多