我有上述条件
物料编码        即时库存      在单数量     安全库存     
1.02.02.001       100            20           50         
1.03.02.001        50            10           50     
1.02.02.002       400           100          100         
1.03.02.002       200           50           100          如何做成下面这张表物料编码        即时库存      在单数量     安全库存     分析
1.02.02.001       100            20           50         
1.03.02.001        50            10           50         
合计              150            30           50         20
1.02.02.002       400           100          100         
1.03.02.002       200           50           100        
合计              600           150          100         250

解决方案 »

  1.   

    ----------------------------------------------------------------
    -- Author  :fredrickhu(我是小F,向高手学习)
    -- Date    :2010-01-25 16:28:38
    -- Version:
    --      Microsoft SQL Server 2005 - 9.00.4035.00 (Intel X86) 
    -- Nov 24 2008 13:01:59 
    -- Copyright (c) 1988-2005 Microsoft Corporation
    -- Developer Edition on Windows NT 5.2 (Build 3790: Service Pack 1)
    --
    ----------------------------------------------------------------
    --> 测试数据:[tb]
    if object_id('[tb]') is not null drop table [tb]
    go 
    create table [tb]([物料编码] varchar(11),[即时库存] int,[在单数量] int,[安全库存] int)
    insert [tb]
    select '1.02.02.001',100,20,50 union all
    select '1.03.02.001',50,10,50 union all
    select '1.02.02.002',400,100,100 union all
    select '1.03.02.002',200,50,100
    --------------开始查询--------------------------
    select
      case when grouping(right(物料编码,6))=1 then '合计' else 物料编码 end as 物料编码,
      sum(即时库存) as 即时库存,sum(在单数量) as 在单数量,sum(安全库存) as 安全库存
    from
      tb
    group by
      right(物料编码,6),物料编码
    with rollup
    ----------------结果----------------------------
    /* 物料编码        即时库存        在单数量        安全库存
    ----------- ----------- ----------- -----------
    1.02.02.001 100         20          50
    1.03.02.001 50          10          50
    NULL        150         30          100
    1.02.02.002 400         100         100
    1.03.02.002 200         50          100
    NULL        600         150         200
    合计          750         180         300(7 行受影响)
    */
      

  2.   

    分析字段:
    貌似
    安全库存>在单数量 求差
    安全库存<在单数量 求和
      

  3.   

    这个得用到grouping函数了。不过如何根据材料编号分组,楼主能给出个条件理由吗?
      

  4.   


    SQL宝典(中文版) 高清PDF版下载