Case Statement query help

Anonymous
2022-08-23T16:02:13.89+00:00

Is it possible to use case more than once in an expression?
I have a query that calculates the cost of insurance.
but i need to see if i can add a *Case statement to my query. like so -----(SUM(ROUND(mnyInsurance,2)*CASE WHEN decInsuranceShare IS NOT NULL THEN 1-decInsuranceShare ELSE 0.60 END),0) Insurance

SELECT
'Cost of Insurance' AS strType,
ISNULL(SUM(CASE WHEN dtReport = @EndDate THEN ROUND(mnyInsurance,2) ELSE 0 END),0) AS intDT,
ISNULL(SUM(CASE WHEN dtReport BETWEEN tblDate.dtFirstDayOfMonth AND @EndDate THEN ROUND(mnyInsurance,2) ELSE 0 END),0) AS intMTD,
ISNUll(SUM(CASE WHEN dtReport BETWEEN tblDate.dtFirstDayOfQuarter AND @EndDate THEN ROUND(mnyInsurance,2) ELSE 0 END),0) AS intQTD,
IsNull(SUM(CASE WHEN dtReport BETWEEN tblDate.dtFirstDayOfYear AND @EndDate THEN ROUND(mnyInsurance,2) ELSE 0 END),0) AS intYTD,
-----(SUM(ROUND(mnyInsurance,2)*CASE WHEN decInsuranceShare IS NOT NULL THEN 1-decInsuranceShare ELSE 0.60 END),0) Insurance

3 as intOrder
FROM
tblUBMReport WITH (NOLOCK)
LEFT JOIN tblUBMInsuranceShare ON tblUBMInsuranceShare.intProp = tblUBMReport.intProp
INNER JOIN tblDate WITH (NOLOCK) ON tblDate.dtDate = @EndDate
WHERE
intProp IN (@Props)

Developer technologies | Transact-SQL
{count} votes

1 answer

Sort by: Most helpful
  1. LiHongMSFT-4306 31,566 Reputation points
    2022-08-24T02:09:15.827+00:00

    Hi @Jannette Jones

    if i can add a *Case statement to my query. like so -----(SUM(ROUND(mnyInsurance,2)*CASE WHEN decInsuranceShare IS NOT NULL THEN 1-decInsuranceShare ELSE 0.60 END),0) Insurance

    Yes, you can use Case When statement as a multiplier in a multiplication expression, provided thatCaseWhen does not return a null value.
    Check this sample:

    CREATE TABLE TEST(ID INT,SCORE INT)  
    INSERT INTO TEST VALUES  
    (1,92),(2,90),(3,89),(4,94),(5,86),(6,83)  
      
    SELECT ID  
          ,SUM(CASE WHEN SCORE=100 THEN SCORE ELSE 100 END*CASE WHEN SCORE>90 THEN SCORE ELSE 90 END)  
    FROM TEST  
    GROUP BY ID  
    

    Best regards,
    LiHong

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.