问题
Consider a table with a column amount,
Amount
-1235.235
1356.45
-133.25
4565.50
5023
-8791.25
I want to my result pane to be like this,
Debit Credit
0 -1235.235
1356.45 0
0 -133.25
Here is my stored procedure,
USE [HotelBI_CustomDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[SP_GetJVReport](
@p_FromDate datetime,
@p_ToDate datetime
)
AS
BEGIN
select jv.AccountNo,jv.AccountNoTitle,(select JV_GroupsHead.GroupTitle
from JV_GroupsHead where JV_GroupsHead.Id=jv.GroupId) as 'GroupName'
,jv.Revenue --" This column i need to check and have to split it into two
column "credeit,debit""
from JVFunction1(@p_FromDate,@p_ToDate) as jv
END
How to write a select statement such that it uses a case like amount>=0 as credit and amount <0 as debit?
回答1:
Modify as needed for your exact needs
SELECT
CASE WHEN Amount < 0 THEN ABS(Amount) ELSE NULL AS Debit,
CASE WHEN Amount >= 0 THEN Amount ELSE NULL AS Credit
FROM
SomeTable
回答2:
Do you mean like this, a separate column to indicate the type of the amount?
SELECT Amount, CASE WHEN Amount < 0 THEN 'Debit' ELSE 'Credit' END AS Type
FROM SomeTable
回答3:
I'd probably create a User-Defined Function to make this a bit easier.
eg.
create function dbo.CreditOrDebit (@amount decimal(9,2), @type char(6))
returns decimal(9,2)
as
begin
declare @output decimal(9,2);
select @output =
case @type
when 'debit' then
case
when @amount < 0.00 then ABS(@amount)
else 0
end
else
case
when @amount >= 0.00 then ABS(@amount)
else 0
end
end;
return @output;
end
Then use it in your Select statement like this:
select jv.AccountNo,jv.AccountNoTitle,(select JV_GroupsHead.GroupTitle
from JV_GroupsHead where JV_GroupsHead.Id=jv.GroupId) as 'GroupName'
,dbo.CreditOrDebit(jv.Revenue,'debit') as debit
,dbo.CreditOrDebit(jv.Revenue,'credit') as credit
来源:https://stackoverflow.com/questions/3759167/using-case-in-a-sql-select-statement