views:

47

answers:

3

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  A: 

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
AdaTheDev
@Ada not the type of amount, `Amount` column should be displayed as two diff Debits and Credits column
Pandiya Chendur
@Pandiya: Perhaps you could update your question to actually show your desired output?
DanP
@DanP i ve edited my question...
Pandiya Chendur
@Pandiya - ah OK. Check out gbn's answer - that'll do the job
AdaTheDev
+4  A: 

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
gbn
A: 

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
Paul Spangle
Scalar UDFs have some overhead. This will be a lot slower over larger recordsets than inline CASE.
gbn
I knew that was the case if the the UDF contained DML, but I've never noticed any difference when the UDF was just doing some sums like this one is. Any idea why it should be slower?
Paul Spangle