我有两张表A,B
A表 有 Num,Type,MainNum,OperaName
B表有  Num,CostName,ShouldMoney,RealMoney,CostType(标示应收应付(1,0)),FlagClosIng我想查出这样的格式
Num,Type,MainNum,OperaName,CostName,ShouldMoney(应收金额),RealMoney(实收金额),ShouldMoney(应付金额),RealMoney(实付金额),FlagClosIng让应收和应付显示在一行,求高手给个sql语句

解决方案 »

  1.   

    根据你的描述,我觉得应该就是B表根据CostType字段分成2组数据,然后再连接就行了,问题是他们连接的条件是什么?Num么?
      

  2.   

    select NUM,TYPE,MainNum,OperaName,CostName,
    (case CostType when 1 then RealMoney end) as RealMoney(实付金额),
    (case CostType when 1 then ShouldMoney end) as ShouldMoney(应付金额),
    (case CostType when 0 then ShouldMoney end) as RealMoney(实收金额),
    (case CostType when 0 then ShouldMoney end) as ShouldMoney(应收金额)
    from A join B
    on A.NUM=B.NUM

      

  3.   

    这样试试;WITH aaa AS
    (
    select Num,CostName,
    (case CostType when 1 then RealMoney end) as RealMoney(实付金额),
    (case CostType when 1 then ShouldMoney end) as ShouldMoney(应付金额),
    (case CostType when 0 then ShouldMoney end) as RealMoney(实收金额),
    (case CostType when 0 then ShouldMoney end) as ShouldMoney(应收金额)
    from B 
    GROUP BY Num,CostName
    )
    SELECT * FROM A INNER JOIN aaa AS B ON A.Num=B.Num
      

  4.   

    目测楼上的可能会报错,稍微改动一下
    ;WITH aaa AS
    (
    select Num,CostName,
    sum(case CostType when 1 then RealMoney else 0 end) as RealMoney(实付金额),
    sum(case CostType when 1 then ShouldMoney else 0 end) as ShouldMoney(应付金额),
    sum(case CostType when 0 then RealMoney else 0 end) as RealMoney(实收金额),
    sum(case CostType when 0 then ShouldMoney else 0 end) as ShouldMoney(应收金额)
    from B 
    GROUP BY Num,CostName
    )
    SELECT 
        a.NUM,TYPE,MainNum,OperaName,CostName,RealMoney(实付金额),
    ShouldMoney(应付金额),RealMoney(实收金额),ShouldMoney(应收金额)
    FROM A INNER JOIN aaa AS B ON A.Num=B.Num
      

  5.   

    ╮(╯▽╰)╭  高手 还是不好用 ;with CostInfo as 
    (select BusinessNum,CostName,Currency_Name,BillNumber,Paymode,CheckNumber
    ,ClosingCostMan,ClosingCostDate,Re
    ,sum(case CostType when '0' then ShouldMoney else 0 end ) as '应收金额'
    ,sum(case CostType when '0' then RealMoney else 0 end ) as '实收金额'
    ,sum(case CostType when '1' then ShouldMoney else 0 end ) as '应付金额'
    ,sum(case CostType when '1' then RealMoney else 0 end ) as '实付金额'
    from Cost_FeeInfo
    group by BusinessNum,CostName,Currency_Name,BillNumber,Paymode,CheckNumber
    ,ClosingCostMan,ClosingCostDate,Re
    )
    select bbd.BusinessNum,BusinessType,Operate_Name,MainListNumber,CostName,应收金额,实收金额,应付金额,实付金额,Currency_Name,BillNumber,Paymode,CheckNumber
    ,ClosingCostMan,ClosingCostDate,Re
    from bus_BusinessDetail as bbd
    inner join CostInfo as ci on ci.BusinessNum = bbd.BusinessNum
    where bbd.Operate_Name ='牡丹江市天业进出口有限责任公司'
      

  6.   

    因为你在with表里多了一些字段,导致了两种方式不能想加