费用编码 费用金额 计划金额 标志(动态显示出是计划内还是计划外)
01 100 300 计划内
03 200 200 计划内
01 300 300 计划外
02 50 100 计划内
01 200 300 计划外
03 200 200 计划外
现在的问题就是同一个表中的费用编码,和计划金额相同的就把费用金额相加出来一个数然后再和计划数相比如果>就是计划外,用SQL怎么逐行判断?
01 100 300 计划内
03 200 200 计划内
01 300 300 计划外
02 50 100 计划内
01 200 300 计划外
03 200 200 计划外
现在的问题就是同一个表中的费用编码,和计划金额相同的就把费用金额相加出来一个数然后再和计划数相比如果>就是计划外,用SQL怎么逐行判断?
解决方案 »
- sql 联合语句拼接问题
- 求助~关于sqlserver2005日期类型的操作加减
- 实现ID大小交替 的SQL!!
- 求一个SQL语句
- windows 2003 server 的密码修改后怎么sql 2000 的服务管理器就不能启动了
- Sql Server 2008 服务启动不了,登录失败!
- sql server2005 无法新建查询 (急!在线等)
- 操作符类型不匹配
- 怎样把EXCEL表中的数据导入到SQL Server表中?要求不用工具,只用代码实现。而且不是逐条记录读取,是一次性导入 。
- 关于SQL Server和Oracle 在半连接方面的问题
- 关于插入数据的问题
- 如何在SQL中实现模糊查询,返回结果是一整行?
-- Author: HEROWANG(让你望见影子的墙)
-- Date : 2009-12-13 17:30:09
-- blog : blog.csdn.net/herowang
---------------------------------
IF OBJECT_ID('[tb]') IS NOT NULL
DROP TABLE [tb]
go
CREATE TABLE [tb] (费用编码 VARCHAR(2),费用金额 INT,计划金额 INT)
INSERT INTO [tb]
SELECT '01',100,300 UNION ALL
SELECT '03',200,200 UNION ALL
SELECT '01',300,300 UNION ALL
SELECT '02',50,100 UNION ALL
SELECT '01',200,300 UNION ALL
SELECT '03',200,200select * from [tb]
;
with
wang1 as (select row=row_number() over(partition by 费用编码 order by getdate()),* from tb),
wang2 as (select 费用编码,费用金额=(select sum(费用金额) from wang1 where 费用编码=t.费用编码 and row<=t.row) ,计划金额
from wang1 t)
select *,标志=case when 费用金额<=计划金额 then '计划内' else '计划外' end from wang2费用编码 费用金额 计划金额 标志
01 100 300 计划内
01 400 300 计划外
01 600 300 计划外
02 50 100 计划内
03 200 200 计划内
03 400 200 计划外
create table #t2 (sn int identity(1,1), feecode varchar(2) , fee int default (0) ) --费用明细表insert into #t1
select '01',300 union all
select '02',100 union all
select '03',200
insert into #t2
select '01',100 union all
select '03',200 union all
select '01',300 union all
select '02',50 union all
select '01',200 union all
select '03',200
--费用明细视图
select #t2.feecode,#t2.fee,#t1.feeplan,(case when (select sum(a.fee) from #t2 a where a.feecode=#t1.feecode and a.sn <=#t2.sn) <#t1.feeplan then '计划内' else '计划外' end) as flags
from #t2 inner join #t1 on #t2.feecode = #t1.feecodedrop table #t1
drop table #t2结果如下:
feecode fee feeplan flags
------- ----------- ----------- ------
01 100 300 计划内
03 200 200 计划外
01 300 300 计划外
02 50 100 计划内
01 200 300 计划外
03 200 200 计划外
判断的地方我写错误了,和计划相等时应该是 计划内--费用明细视图
select #t2.feecode,#t2.fee,#t1.feeplan,
(case when (select sum(a.fee) from #t2 a where a.feecode=#t1.feecode and a.sn <=#t2.sn) <=#t1.feeplan then '计划内' else '计划外' end) as flags
from #t2 inner join #t1 on #t2.feecode = #t1.feecode
feecode fee feeplan flags
------- ----------- ----------- ------
01 100 300 计划内
03 200 200 计划内
01 300 300 计划外
02 50 100 计划内
01 200 300 计划外
03 200 200 计划外