zoukankan      html  css  js  c++  java
  • SQL中临时表和运算的运用

    已知表结构 C(C1, C2, C3), 其中 C1 为自增列,数据如下:
    C1 C2 C3
    1 10 2
    2 20 10
    3 30 10
    4 30 10

    现想根据已知数据生成 C4 字段:
    当 C1 = 1 时 C4 = 10 - 2 = 8
    当 C1 = 2 时 C4 = (20 + 10) - (10 + 2) = 18
    当 C1 = 3 时 C4 = (30 + 20 + 10) - (10 + 10 + 2) = 38
    当 C1 = 4 时 C4 = (30 + 30 + 20 + 10) - (10 + 10 + 10 + 2) = 58

    也就是说 C4 的值是 SUM(C2-C3), 但不包括当前值以后的值,对应的 SQL 语句如下:
    select c1,c2,c3,(
        select sum(c2-c3)
        from c cb
        where cb.c1<=ca.c1) c4
    from c ca

    最终结果:
    C1 C2 C3 C4
    1 10 2 8
    2 20 10 18
    3 30 10 38
    4 30 10 58

    对于 C1 没有索引的情况下,比如数据为:
    C1 C2 C3
    1 10 2
    4 20 10
    3 30 10
    2 30 10

    这种情况可以采用临时表或表变量的方法,把数据先导入到临时表或表变量,并增加一自增列,临时表语句如下:
    create table #tmp
    (
         ta int identity(1,1),
         c1 int,
         c2 int,
         c3 int
    )
    insert into #tmp (c1,c2,c3) select c1,c2,c3 from c

    select c1, c2, c3,(
        select sum(c2-c3)
        from #tmp cb
        where cb.ta<=ca.ta) c4
    from #tmp ca

    drop table #tmp

    表变量语句如下:
    declare @tmp table
    (
         ta int identity(1,1),
         c1 int,
         c2 int,
         c3 int
    )
    insert into @tmp (c1,c2,c3) select c1,c2,c3 from c


    select c1, c2, c3,(
        select sum(c2-c3)
        from @tmp cb
        where cb.ta<=ca.ta) c4
    from @tmp ca


    最终结果:
    C1 C2 C3 C4
    1 10 2 8
    4 20 10 18
    3 30 10 38
    2 30 10 58

  • 相关阅读:
    源码搭建zabbix平台
    如何用手机远程控制自己的电脑
    nginx无法启动问题详解
    在<script>中加HTML注释标签<!-- --> 的原因?
    UNICODE,GBK,UTF-8区别
    dart学习一 windows环境安装dart环境
    Git使用方法(精心整理,绝对够用)
    非常好用的jQuery表格排序插件
    Redis NOAUTH Authentication required.
    Docker概念、安装
  • 原文地址:https://www.cnblogs.com/yangbin1005/p/994207.html
Copyright © 2011-2022 走看看