表TD 是一个收费记录表
SfLsh(字符),Je,Jsfs,Xj
字段含义
SfLsh: 收费流水号,Je 收费的总金额。jsfs: 结算方式 包括 '现金','刷卡','支票'。Xj: 收费现金部分。
示例数据:
 sflsh    je  jsfs xj
'NO0001',150,现金,150  --全部用现金支付
'NO0002',150,刷卡,0    --全部用刷卡支付
'NO0003',150,刷卡,50   --刷卡支付100,现金支付50,(因为卡上只有100,其它的付现金)
'NO0004',150,支票,0    --全部用支票支付
。。要求:
写一条查询SQL语句 返回一条记录 汇总TC表中现金多少,刷卡多少,支票多少,总金额多少,结果如下:
现金    刷卡  支票  总金额
200     250   150   600
方法1
三个子查询 select a.ZJE,b.SKJE,b.SKFXJ,c,ZP,( a.ZJE+b.SKJE+b.SKFXJ+c,ZP)as HZ from
((select sum(JE) as ZJE from TD where JSFS='现金' group by JSFS) a,
(select sum(JE-XJ) as SKJE ,SUM(XJ) as SKFXJ from TD where JSFS='刷卡' group by JSFS) b,
(select sum(JE) as ZP from TD where JSFS='支票' group by JSFS) c)
还可以用哪种方法得到 那个结果?

解决方案 »

  1.   

    本帖最后由 josy 于 2011-05-04 21:24:58 编辑
      

  2.   

    ---测试数据---
    if object_id('[TD]') is not null drop table [TD]
    go
    create table [TD]([sflsh] varchar(6),[je] int,[jsfs] varchar(4),[xj] int)
    insert [TD]
    select 'NO0001',150,'现金',150 union all
    select 'NO0002',150,'刷卡',0 union all
    select 'NO0003',150,'刷卡',50 union all
    select 'NO0004',150,'支票',0
     
    ---查询---
    select 
      现金=sum(case when JSFS='现金' then JE else 0 end),
      刷卡=sum(case when JSFS='刷卡' then JE-XJ else 0 end),
      支票=sum(case when JSFS='支票' then JE else 0 end),
      总金额=SUM(JE)
    from TD
    ---结果---
    现金          刷卡          支票          总金额
    ----------- ----------- ----------- -----------
    150         250         150         600(1 行受影响)
      

  3.   

    select 
      现金=sum(case when JSFS='现金' then JE else 0 end),
      刷卡=sum(case when JSFS='刷卡' then JE-XJ else 0 end),
      支票=sum(case when JSFS='支票' then JE else 0 end),
     总金额=sum(JE)
    from TD