zoukankan      html  css  js  c++  java
  • 利用聚合函数和子查询简单实现数据迭代查询

    几个月前面试第一次遇到这种题目

    大意是每行记录的某一列和下一行记录的某列之和,做为一个新列保存到结果集中,以此类推

    现在想想,竟然是如此的简单,并且实现方式不仅一种!

    --测试数据
    declare @tempTable table(id int primary key identity, price int)
    insert into @tempTable select 3 union all select 20 union all select 6 union all select 12


    select * from @tempTable


    --执行查询
    select a.*, (select sum(price) from @tempTable where id <= a.id) totalPrice from @tempTable a

    先看看结果如下

     

    新结果集的第三列是id小于当前行id的所有price之和,

    这好像跟普通的查询没有什么区别,只是子查询中查询的对象是本身,让人有点不太习惯,就好像递归一样,

    自己调用自己,如果下次面试遇到这种题目,一定会正确的完成,哈哈!

    继续接着写下一种实现方式,先看代码

    --测试数据
    declare @tempTable table(id int primary key identity, price int)
    insert into @tempTable select 3 union all select 20 union all select 6 union all select 12

    ;
    with tt as
    (
        
    select a.*, price as totalPrice from @tempTable a where id = 1
        
    union all
        
    select a.*, a.price + t.totalPrice from @tempTable a, tt t where a.id = t.id + 1
    )
    select * from tt

    这是种比较无聊的实现方式,因为写法没有第一种简单,性能也不见得有优势,完全是为了学习with的用法!

    with是sql 2005的新特性, 叫公共表达式(CTE),可以在里面递归实现迭代查询效果,结果跟上图一样

  • 相关阅读:
    STM32 变量无法赋值问题
    ROS 多台计算机联网控制机器人
    Content-Disposition
    Arrays.asList()与toArray()
    length与size()
    computeIfAbsent
    共享锁、排他锁与意向锁
    行锁、页面锁与表锁
    classpath是什么
    start、run、join
  • 原文地址:https://www.cnblogs.com/fengxiang/p/1541823.html
Copyright © 2011-2022 走看看