我在 SQL 中有一个查询,我在其中显示一个人是否有付款或未结费用。在这个查询中,我有一个案例语句,但我需要将记录组合在一起以确保将付款添加在一起,以便我检查的内容是正确的。
让我展示一下代码,希望这会更有意义。
这是我目前正在使用的查询:
Declare @tmpTable Table
(
[Bid #] int,
Name varchar(200),
Spent numeric(18,2),
Paid numeric(18,2),
[Credit Card On File] varchar(3),
SaleCounter int,
Notes varchar(max)
)
Insert into @tmpTable([Bid #], Name, Spent, Paid, [Credit Card On File], SaleCounter, Notes)
Select s.[BidderNumber] as 'Bid #', ltrim(rtrim(b.bidderName)) as 'Name', isnull(s.saleprice * s.Quantity,0) as 'Spent',
isnull(t.Amount,0) as 'Paid',
case
when b.cconfile = 1 then 'Yes'
else
'No'
end as 'Credit Card On File',
s.SaleCounter, isnull(t.Notes, '') as 'Notes'
from sales s inner join Bidders b on s.BidderNumber = b.BidderNumber
Left outer join transactions t on t.BidderNumber = s.BidderNumber
order by s.Biddernumber, b.biddername, b.cconfile, SaleCounter
Select [Bid #], Name, Spent as 'Total Purchases', Paid as 'Current Payments',
case
when [Credit Card On File] = 'Yes' then
case
when cast(Paid as numeric(18,2)) = 0 then cast(Spent as numeric(18,2))
else
case when (sum(cast(Paid as numeric(18,2)))) > sum(cast(Spent as numeric(18,2))) then (cast(Paid as numeric(18,2)))- sum(cast(Spent as numeric(18,2)))
else (cast(Spent as numeric(18,2)) - cast(Paid as numeric(18,2)))
end
end
else 0
end as 'Amount To Charge Credit Card',
case
when [Credit Card On File] = 'No' then
case
when cast(Paid as numeric(18,2)) = 0 then cast(Spent as numeric(18,2))
else
case when (sum(cast(Paid as numeric(18,2)))) > sum(cast(Spent as numeric(18,2))) then (cast(Paid as numeric(18,2)))- sum(cast(Spent as numeric(18,2)))
else (cast(Spent as numeric(18,2)) - cast(Paid as numeric(18,2)))
end
end--sum(Outstanding)
ELSE 0
end as 'Outstanding Balance', Notes
from @tmpTable
group by [Bid #], name, spent, paid, [Credit Card On File], SaleCounter, Notes
order by [Bid #], Name, spent, paid, [Credit Card On File], SaleCounter, Notes
这是返回并插入到@tmpTable 中的记录集:
Bid # Name Total Purchases Current Payments Amount To Charge Credit Card Outstanding Balance Notes
101 Tom & Joan Bergland 7500.00 0.00 0.00 7500.
102 John & Bonnie Black 50.00 50.00 0.00 0.00
108 Cindy Davidson 3600.00 1600.00 0.00 2000.00 250
108 Cindy Davidson 3600.00 2000.00 0.00 1600.00
109 Cynthia Davis 315.00 315.00 0.00 0.00 2355
117 Susan Harris 75.00 75.00 0.00 0.00
119 Jim & Julie Hill 520.00 0.00 520.00 0.00
125 Bill & Amy Lee 526.00 526.00 0.00 0.00
现在我的问题是,当没有欠款时,我显示的是 108 号投标所欠的余额。这两个记录反映了对余额进行的两次付款,当两者合计时,它们等于余额。我需要向用户显示每笔付款,但是当付款等于总购买金额时,则不需要显示所欠余额。但是,如果存在平衡,则需要显示出来。(信用卡付款不同......我遇到的问题是非 CC 付款)
有没有办法在 case 语句中进行分组,或者我缺少的 sql 中有什么东西可以让我需要发生的事情?
我提前感谢您的帮助。