首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

怎么用一条 SQL语句 或者 自定义函数/存储过程 实现这个过滤查询? *100分*

2012-01-13 
如何用一条 SQL语句 或者 自定义函数/存储过程 实现这个过滤查询? *****100分***** 表T_PaymentSID(不重复

如何用一条 SQL语句 或者 自定义函数/存储过程 实现这个过滤查询? *****100分*****

表     T_Payment

SID(不重复)               Amount                     Is_Credit
========================================
1                               150.00                       0
2                               100.00                       0
3                               100.00                       0
4                               100.00                       1
5                               100.00                       1

在上面的表中,
Is_Credit   =0   表示应收项
Is_Credit   =1   表示付款数

我需要找出所有 "还未被付款 "的记录,   上面表中,隐含表示:   SID=2,3的记录   已经被   SID=   4,5   的记录结帐了.   结帐的记录之间没有一个对应的结帐勾对的标志,所以只能用金额对冲算出

在本例中,   我要找出的满足我的条件的记录是只有   SID   =1   的如下一条记录.

SID                           Amount                     Is_Credit
========================================
1                               150.00                       0


如何用一条   SQL语句   或者   自定义函数/存储过程   实现这个过滤查询?

谢谢   各位高手!

[解决办法]
--create test environment
declare @t table(SID int,Amount money,Is_Credit bit)
insert into @t
select 1, 150.00, 0 union all
select 2, 100.00, 0 union all
select 3, 100.00, 0 union all
select 4, 100.00, 1 union all
select 5, 100.00, 0 union all
select 6, 100.00, 0

--query
select
sid,amount,is_credit
from @t a
where is_credit=0 and
(select count(9) from @t where is_credit=1 and amount=a.amount) <=(select count(9) from @t where is_credit=0 and amount=a.amount and sid <a.sid)

--result
/*
sid amount is_credit
--- ------ ---------
1150.000
3100.000
5100.000
6100.000
*/
[解决办法]
学习
[解决办法]
---刪除一條數據做測試

--創建測試環境
Declare @TEST Table(SID Int, Amount Money, Is_Credit Bit)
Insert Into @TEST Select 1, 150.00, 0
Union All Select 2, 100.00, 0
Union All Select 3, 100.00, 0
Union All Select 4, 100.00, 1

--測試
Select * From @TEST A
Where (Select Count(SID) From @TEST Where Amount = A.Amount And SID <= A.SID And Is_Credit = 0)


> (Select Count(SID) From @TEST Where Amount = A.Amount And Is_Credit = 1)
And Is_Credit = 0
--結果
/*
SIDAmountIs_Credit
1150.00000
3100.00000

*/

[解决办法]
鱼兄的創建測試環境 很好用``呵呵``又学到了一招``

热点排行