现有一表A,字段及内容如下:Val    Seller     Buyer
===========================
100     上海       江苏80      浙江       上海70      江苏       浙江...--------------------------------------------------
要实现:查询上海总共的Val值
(注:这里包括上海作为Seller和Buyer的情况,当上海作为Seller时值为正,即100;当上海作为Buyer时值为负,即-80)最终需要的查询结果是:(Sell-Buy 即 100-80)Val     Player
=======================
20       上海同理,如果查询江苏的结果则一个是:(Sell-Buy 即 70-100)Val     Player
=======================
-30       江苏
如果查询浙江的结果则一个是:(Sell-Buy 即 80-70)Val     Player
=======================
10       浙江
-----------------------------------------------------------------------------------------原先是想可以通过两次select分别查处Sell和Buy,如何让程序来处理加减的;
现在要求一次查询得出最终结果。不知道这个sql该怎么写。。请各位帮忙看看,不吝指教。

解决方案 »

  1.   

    select name , sum(val) val from
    (
    select Val ,Seller name from a
    union all
    select - Val ,Buyer name from a
    ) t
    group by name
      

  2.   

    create table a(Val int,Seller varchar(10),Buyer varchar(10))
    insert into a values(100 ,'上海', '江苏')
    insert into a values(80  ,'浙江', '上海')
    insert into a values(70  ,'江苏', '浙江')
    goselect name , sum(val) val from
    (
    select Val ,Seller name from a
    union all
    select - Val ,Buyer name from a
    ) t
    group by namedrop table a/*
    name       val         
    ---------- ----------- 
    江苏         -30
    上海         20
    浙江         10(所影响的行数为 3 行)
    */
      

  3.   

    谢谢楼上,吃饭回来后我试下。
    我的数据库不是MSSQL哦~
    也不是MySQL、Oracle、DB2等
    是个国产的数据库,应该没什么问题的吧?
      

  4.   

    create table a(val int,seller nvarchar(10), buyer nvarchar(10))
    insert a
    select 100 ,N'上海' ,N'江苏' union allselect 80 ,N'浙江' ,N'上海' union allselect 70 ,N'江苏' ,N'浙江'
    go
    select city,sum(val) from
    (
    select val* (-1) as val,buyer as city  from a 
    union all 
    select val ,seller as city from a
    )t1 group by city
    go
    结果:江苏 -30
    上海 20
    浙江 10