SQL Server Make CASE for only specified Condition

ubof19bj  于 2023-04-04  发布在  其他
关注(0)|答案(2)|浏览(142)

I have a table that has 2 columns : Balance , RateCol

I want to make a query, with condition like this

X is 2.25
when Balance > 0 then Total = Balance, and RateCol > X
When Balance > 2000000000 then Total = Balance - 2000000000, and RateCol <= X

The first thing I tried is using CASE , but the result is not like what I wanted

Query :

SELECT 
    Balance, 
    CASE 
        WHEN Balance > 0 AND RateCol > 2.25 THEN Balance
        WHEN Balance > 2000000000 AND RateCol <= 2.25 THEN Balance - 2000000000 
    END AS Total,
    RateCol
FROM
    MyTable

Result:

BalanceTotalRateCol
4428600457.502428600457.501.400000
15339365000.0015339365000.003.250000
335500000.00NULL0.750000 < Anomaly
347188820.00NULL0.750000 < Anomaly

As you can see from my result, the anomalies somehow also get included even thought it's outside of my defined scope.

What I thought is this happening because I didn't defined ELSE for condition I didn't specify, but I only need result from the condition I did specify, is there a way to achieve this?

I've also tried to add WHERE on my query like this :

SELECT 
    Balance, 
    CASE 
        WHEN Balance > 0 THEN Balance
        WHEN Balance > 2000000000 THEN Balance - 2000000000 
    END AS Total,
    RateCol
FROM  
    MyTable
WHERE
    RateCol = CASE 
                  WHEN Balance > 0 THEN RateCol > 2.25
                  WHEN Balance > 2000000000 THEN RateCol <= 2.25

But CASE cannot take comparison expression, and I don't know what to do anymore

Expected result :
| Balance | Total | RateCol |
| ------------ | ------------ | ------------ |
| 4428600457.50 | 2428600457.50 | 1.400000 |
| 15339365000.00 | 15339365000.00 | 3.250000 |

(Anomalies not included)

osh3o9ms

osh3o9ms1#

WHERE
    RateCol = CASE 
                  WHEN Balance > 0 THEN RateCol > 2.25
                  WHEN Balance > 2000000000 THEN RateCol <= 2.25

Isn't this attempt equivalent to:

WHERE (Balance > 0          AND RateCol >  2.25)
   OR (Balance > 2000000000 AND RateCol <= 2.25)
gorkyyrv

gorkyyrv2#

I think you are correct in thinking that the anomalies are being included because there is no ELSE clause defined in your CASE statement

In the absence of an ELSE clause, NULL is returned for all cases that don't match the specified conditions

What I would do is wrap your query in a subquery -- filter out the rows with NULL values in Total column in the outer query

SELECT Balance, Total, RateCol
FROM (
  SELECT Balance,
    CASE 
      WHEN Balance > 0 AND RateCol > 2.25 THEN Balance
      WHEN Balance > 2000000000 AND RateCol <= 2.25 THEN Balance - 2000000000 
    END AS Total,
    RateCol
  FROM MyTable
) subquery
WHERE Total IS NOT NULL
  • subquery calculates the Total column using the same logic you provided
  • outer query then filters out the rows with NULL values in the Total column, which should exclude the anomalies you mentioned.

相关问题