案例 计算店铺的月销售额和累加到当前月的销售和--SparkSql实现(SQL风格)

数据如下:

shop1,2019-01-18,500
shop1,2019-02-10,500
shop1,2019-02-10,200
shop1,2019-02-11,600
shop1,2019-02-12,400
shop1,2019-02-13,200
shop1,2019-02-15,100
shop2,2019-02-10,100
shop2,2019-02-11,100
shop2,2019-02-13,100
shop2,2019-03-15,100
shop2,2019-04-15,100

/**
 * 计算店铺的月销售额和累加到当前月的销售额
 * shop1,2019-01-18,500
 * shop1,2019-02-10,500
 * shop1,2019-02-10,200
 * shop1,2019-02-11,600
 * shop1,2019-02-12,400
 * shop1,2019-02-13,200
 * shop1,2019-02-15,100
 * shop2,2019-02-10,100
 * shop2,2019-02-11,100
 * shop2,2019-02-13,100
 * shop2,2019-03-15,100
 * shop2,2019-04-15,100
 *
 * 思路:先根据sid,月份聚合销售额
 * 再根据sid分组,日期排序,累加月销售额
 */
object ShopIncomeSQL {
  def main(args: Array[String]): Unit = {
    val session = SparkSession.builder()
      .appName(this.getClass.getSimpleName)
      .master("local[*]")
      .getOrCreate()

    val df = session.read.option("inferSchema", "true")
      .option("header", true)
      .csv("data/shop.txt")
    df.createTempView("tb_shop")

    val tmp1 = session.sql(
      """
        |select
        |  sid,
        |  mth,
        |  sum(money) mth_income
        |from
        |(
        |  select
        |    sid,
        |    substr(ctime,0,7) mth,
        |    cast(money as DOUBLE) money
        |  from
        |    tb_shop
        |)
        |group by sid, mth
        |""".stripMargin)

    tmp1.createTempView("v_tmp1")

    val res = session.sql(
      """
        |select
        |  sid,
        |  mth,
        |  mth_income,
        |  sum(mth_income) over(partition by sid order by mth rows between unbounded preceding and current row) total_money
        |from
        | v_tmp1
        |""".stripMargin)

    res.show()

  }

}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值