如有一张费用表(TPAY),有个客户字段(CUSTID),一个金额字段(MONEY),一个标志字段(FLAG;1:有效;2:失效...),如何在一条语句中根据客户号及标志汇总金额。效果:
客户 有效   失效
X      Y    Z
X1     Y1   Z1
...主要用于报表。

解决方案 »

  1.   

    这样可以吗?  select custid,
         sum(case flag when 1 then 1 else 0 end) as 有效,
         sum(case flag when 2 then 1 else 0 end) as 无效 
      from table group by custid
      

  2.   

    什么数据库阿你没说....太麻烦还要挨个写
    ORACLE:
     select custid,
         sum(decode(flag,1,0,money,0) as 有效,
         sum(decode(flag,0,1,0,money) as 无效 
      from table group by custid
    sqlserver:
    select custid,
         sum(case flag when 1 then 1 else 0 end) as 有效,
         sum(case flag when 2 then 1 else 0 end) as 无效 
      from table group by custid
    DB2:
    select custid,
         sum(case flag when ‘1' then money else 0) as 有效,
         sum(case flag when ‘0' then money else 0) as 无效 
      from table group by custid
      

  3.   

    select custid,
         sum(case flag when 1 then Money else 0 end) as 有效金额,
         sum(case flag when 2 then Money else 0 end) as 无效金额 
      from table group by custid
      

  4.   

    SELECT CustID as 客户,
      有效=SUM(CASE WHEN Flag=1 THEN MONEY ELSE 0 END),
      无效=SUM(CASE WHEN Flag=2 THEN MONEY ELSE 0 END),
    FROM TPAY
    GROUP BY CustID
      

  5.   

    呵,多谢各位。
    望了补充了,我用的数据库是sybase,但版本较低,不支持Case语句。
    有无其它方法?
      

  6.   

    select acustid, amoney, bmoney
    from (select custid acustid, sum(money) amoney
          from table
          where flag = 1),
         (select custid bcustid, sum(money) bmoney
          from table
          where flag = 2)
    where acustid = bcustid没有测试,不知是否可以
      

  7.   

    这个应该是男女老少通吃的吧!
      
      select custid,
         (select sum(money) where custid=a.custid and flag=1) as 有效,
         (select sum(money) where custid=a.custid and flag=2) as 无效 
      from table a group by custid
      

  8.   

    错了,错了,不好意思  select custid,
         (select sum(money) from table where custid=a.custid and flag=1) as 有效,
         (select sum(money) from table where custid=a.custid and flag=2) as 无效 
      from table a group by custid