单据号    商品码                          数量          价格                                  
1 101 1 12.0000 0 1
1 102 1 16.0000 0 1
1 102 1 16.0000 0 1
1 103 1 20.0000 0 1
1 103 1 20.0000 0 1
1 104 1 14.0000 0 1
1 105 1 -5.8 0 -6
5 111 1 2.0000 0 1
4 201 1 4.0000 0 1能否通过语句得到
单据号    商品码                          数量          价格             收入     折扣
1 101 1 12.0000 12 1
1 102 2 16.0000 32 1
1 103 2 20.0000 40 1
1 104 1 14.0000 8 -6
5 111 1 2.0000 0 1
4 201 1 4.0000 0 1
意思就是:生成的表里相同单号里重复的商品码相加不重复的保留,收入=数量*价格,有折扣的收入=数量*价格-折扣
下一单里如果有类似102,103商品,不能统计到单据1中。限制比较多,网上查半天也没合适的答案,来这问问。

解决方案 »

  1.   

    select tempA.单据号,tempA.商品码,tempA.数量,tempB.价格, tempB.价格*tempA.数量 - tempA.折扣 as 收入,tempA.折扣 
    from (select 单据号,商品码, sum(数量) as 数量,sum(折扣) as 折扣 from tableA group by 商品码,单据号) tempA, 
    (select distinct 单据号,商品码,价格 from tableA) tempB
    where tempA.商品码 = tempB.商品码 and tempA.单据号 = tempB.单据号
    我没有测试,你自己测试一下吧,提供给你思路,有问题可以找我
      

  2.   


    你的做法没有按单号排列,也没有把数量相加。where里限制完单号和商品码相同,那个临时的tempA中会SUM么?这俩好像没必然联系吧。。
    我之前列的1和2我认为语句判断上应该有先后顺序,先在同一单,商品码相同(这个where里限制了),其次才是符合这个条件的数量相加,不知道说明白了没。
      

  3.   

    用 
    SQL嵌套然後
    group by  ...
      

  4.   

    select tempA.单据号,tempA.商品码,tempA.数量,tempB.价格, tempB.价格*tempA.数量 - tempA.折扣 as 收入,tempA.折扣  
    from (select 单据号,商品码, sum(数量) as 数量,sum(折扣) as 折扣 from tableA group by 商品码,单据号) tempA,  
    (select distinct 单据号,商品码,价格 from tableA) tempB
    where tempA.商品码 = tempB.商品码 and tempA.单据号 = tempB.单据号
    order by tempA.单据号select 单据号,商品码, sum(数量) as 数量,sum(折扣) as 折扣 from tableA group by 商品码,单据号 这个可以将 相同的商品码和单据号合并将其数量累加
    select distinct 单据号,商品码,价格 from tableA 除去重复的数据,单据号,商品码,价格应该是唯一的吧
    排列你不会吗?别总是在看,你试试吧,不去测试,怎么知道别人的对不对, 还有排序你自己不会吗?
    最外层加order by tempA.单据号不就可以了吗,别人给你的是思路,没有测试环境,需要你自己去验证
    好了,有问题联系我吧我的MSN是[email protected]
      

  5.   

    select tempA.单据号,tempA.商品码,tempA.数量,tempB.价格, tempB.价格*tempA.数量 - tempA.折扣 as 收入,tempA.折扣   
    from (select 单据号,商品码, sum(数量) as 数量,sum(折扣) as 折扣 from tableA group by 商品码,单据号) tempA,   
    (select distinct 单据号,商品码,价格 from tableA) tempB
    where tempA.商品码 = tempB.商品码 and tempA.单据号 = tempB.单据号
    order by tempA.单据号把其中的sum改为count,OK了。
    感谢qingyunzhuimeng) 提供思路,不是很精通SQL的自己写起来会有迷茫的无从下手的感觉,尤其是语法没毛病的时候,运行不出正确的结果。我自己测了好几天了,不是没有试就问。只是希望以后写的时候高手们能提供一个查找原因的思路?缩小解决问题的范围,而不是埋怨和不耐烦,尤其是不经常接触SQL的,自信很重要。
      

  6.   

    解决了就好,不是不耐烦,而是觉得思路给你了,你没有领会,是最让人...,好了,总之弄明白了才是最重要的,有任何问题可以联系我,同上,可以用MSN联系我,不行在CSDN上也可以