日期:2014-05-17  浏览次数:20557 次

求2条综合查询语句
T1
流水号 类型 金额 状态
1 现金 10 有效
2 支票 10 有效
3 转账 10 有效
4 支票 10 作废
5 现金 10 作废
..
T2//只记录支票的信息(现金和转账不记录)
流水号 实扣
2 5
..

第一个结果
流水号范围 总单据数 有效数 合计金额 现金 非现金 无效数
1-5 5 3 30 15 15 2
注意,第二条数据,由于实扣是5,但金额是10,所以有5元当做现金计算


第二个结果
类型分类 单据数 合计 现金 非现金
现金 1 10 10 0
支票 1 10 5 5
转账 1 10 0 10



------解决方案--------------------
select cast(min(t1.流水号) as varchar(50))+'-'+cast(max(t1.流水号) as varchar(50)) 流水号范围
,count(*) 总单据数
,sum(case 状态 when '有效' then 1 else 0 end) 有效数
,sum(case 状态 when '有效' then 金额 else 0 end) 合计金额
,sum(case 状态 when '有效' then (case 类型 when '现金' then 金额 when 支票 then 金额-t2.实扣 else 0 end) else 0 end) 现金
,sum(case 状态 when '有效' then (case 类型 when '转账' then 金额 when 支票 then t2.实扣 else 0 end) else 0 end) 非现金
,sum(case 状态 when '有效' then 0 else 1 end) 无效数
from t1 left join t2 on t1.流水号=t2.流水号
------解决方案--------------------
SQL code
--1
select [流水号范围]=cast((select min([流水号]) from t1) as varchar(10))+'-'+cast((select max([流水号]) from t1) as varchar(10)),
 [总单据数]=(select count(*) from t1),
 [有效数]=(select count(*) from t1 where [状态]='有效'),
 [合计金额]=(select sum(金额) from t1 where [状态]='有效'),
 [现金]=(select sum(t1.金额-isnull(t2.实扣,0)) from t1 left join t2 on t1.[流水号]=t2.[流水号] where t1.[状态]='有效' and t1.[类型] in ('现金','支票'))
 [非现金]=(select sum(金额) from t1 where [状态]='有效' and 类型<>'现金')
            -(select sum(t1.金额-t2.实扣) from t1,t2 where  t1.[流水号]=t2.[流水号] and t1.[状态]='有效' and t1.[类型]='支票')
  [无效数]=(select count(*) from t1 where [状态]='作废')

--2
select 类型 as 类型分类,count(*) as 单据数,sum(t1.金额) as 合计,
    sum(case when 类型='现金' then t1.金额 
        when 类型='支票' then t1.金额-isnull(t2.实扣,0) else 0 end as 现金,
    sum(case when 类型='支票' then isnull(t2.实扣,0) when 类型='转账' then t1.金额 else 0 end as 非现金
from t1 left join t2 on t1.[流水号]=t2.[流水号 where [状态]='有效'