select SerialNO,sum(case uType when 2 then -sNo else sNo end),max(sDate)
from PRS
group by SerialNO

解决方案 »

  1.   

    ----------------------------------------------------------------
    -- Author  :DBA_HuangZJ(發糞塗牆)
    -- Date    :2014-07-07 13:40:35
    -- Version:
    --      Microsoft SQL Server 2012 - 11.0.5058.0 (X64) 
    -- May 14 2014 18:34:29 
    -- Copyright (c) Microsoft Corporation
    -- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
    --
    ----------------------------------------------------------------
    --> 测试数据:[PRS]
    if object_id('[PRS]') is not null drop table [PRS]
    go 
    create table [PRS]([SerialNO] int,[uType] int,[sNO] int,[sDate] datetime)
    insert [PRS]
    select 107792,1,5,'20140609' union all
    select 107792,1,3,'20140609' union all
    select 107792,2,5,'20140610' union all
    select 100785,1,8,'20140610'
    --------------开始查询--------------------------SELECT SerialNO,SUM(sNO)sNO,MAX([sDate])[sDate]
    FROM (
    select SerialNO  ,      sNO   ,[sDate]     from [PRS]
    WHERE utype=1
    UNION ALL 
    select SerialNO  ,    -1*sNO ,[sDate]    from [PRS]
    WHERE utype=2)a
    GROUP BY SerialNO
    ORDER BY SerialNO DESC 
    ----------------结果----------------------------
    /* 
    SerialNO    sNO         sDate
    ----------- ----------- -----------------------
    107792      3           2014-06-10 00:00:00.000
    100785      8           2014-06-10 00:00:00.000
    */
      

  2.   

    SELECT [SerialNO],SUM(CASE uTYPE WHEN 2 THEN -1*sNo ELSE sNo end )AS Quantity,MAX(sDate)sDate
    FROM  A_J
    GROUP BY [SerialNO]
    ORDER BY SerialNo desc