Select SUM(CASE When CPayment='Cash' Then CAmount Else 0 End ) as CashPaymentAmount,
       SUM(CASE When CPayment='Check' Then CAmount Else 0 End ) as CheckPaymentAmount
from TableOrderPayment
Where ( CPayment='Cash' Or CPayment='Check' ) AND CDate<=SYSDATETIME() and CStatus='Active';
Answer from Mudassir Hasan on Stack Overflow
🌐
Interview Query
interviewquery.com › p › sum-case-when-sql
SQL Conditional SUM: SUM(CASE WHEN) Syntax, Examples & Best Practices
March 17, 2026 - In analytics SQL, the fastest way ... often called a SQL conditional sum. It lets you total only the rows that meet a condition (or set of conditions) directly inside a single grouped query....
Discussions

sql server - SUM (CASE WHEN) AS.. query - Database Administrators Stack Exchange
I'm very new to SQL and I'm trying and failing to get the right syntax on what I presumed would be a pretty easy query. I have a table (CustomerSales) with four columns: Period: a combination of y... More on dba.stackexchange.com
🌐 dba.stackexchange.com
July 5, 2016
group by - Sum(Case When) Question - Database Administrators Stack Exchange
I'm trying to get the syntax correct on my query but I'm having issues. Currently my query will show the Household Total Value (HHValue) and then the NationalValue on one row, then the second row... More on dba.stackexchange.com
🌐 dba.stackexchange.com
Conditional Sum Syntax Are these two methods both correct or do they calculate or return results differently?
Method_1=Case when WS_Cost_Code = 1 then SUM(WS_Extended) else 0 end Method_2=SUM(case when WS_Cost_Code=1 then WS_Extended_Cost else 0 end ) More on learn.microsoft.com
🌐 learn.microsoft.com
3
0
October 21, 2021
Using SUM() In CASE Statement / Best Practices – SQLServerCentral Forums
If I'm reading your code correctly, ... 1 in the case statement instead of the partition by as batchsdsid is unique, it won't have more than one status, I don't need a running total of that here. However, the CTE makes sense as it gives the specific subset of batches that are in scope for the query (I discovered that my data has future dates that aren't in scope). The main performance drag is the SORT operation that comes into the execution plan when I SUM the trans.Capital ... More on sqlservercentral.com
🌐 sqlservercentral.com
November 6, 2018
🌐
Reddit
reddit.com › r/sql › sum and case when
r/SQL on Reddit: SUM and CASE WHEN
February 1, 2022 -

Trying to find different ways to find the number of male customers, the first way

SELECT COUNT(*) AS num_studend_male
  FROM performance
 WHERE gender = 'male';

and the second way.

SELECT SUM(
         CASE
           WHEN (gender = 'male') THEN 1
           ELSE 0
         END 
       ) AS num_studend_male
  FROM performance;

In my second query, how could I count females as well, and add it as a separate column? Is this even possible?

🌐
LearnSQL.com
learnsql.com › blog › case-when-with-sum
How to Use CASE WHEN With SUM() in SQL | LearnSQL.com
December 15, 2020 - Exactly, it’s the same as if ... 20. Using a CASE WHEN expression to assign values 0 or 1 to the table rows is just a little trick to make SUM() return the number of rows just like the COUNT() function would...
🌐
Medium
michael-taverner.medium.com › advanced-uses-of-the-case-statement-in-sql-part-1-a8ae4af8dd95
Advanced uses of the CASE statement in SQL — Part 1: SUM(CASE WHEN) | by Michael Taverner | Medium
May 15, 2022 - Let’s do that by grouping on the stock code and description columns, then adding 4 columns with the SUM of sales in each market. We’ll then ORDER BY the UK sales amount, in descending order. ... Because we want to split the sales per market into individual columns and only look at Unit prices, our CASE statement specifies the country and the “type” as Unit Price, then returns the Amount to the SUM function.
🌐
Modern SQL
modern-sql.com › excel › sumif-in-sql
SUMIF in SQL: SUM(CASE WHEN <condition> THEN <value> END)
The Microsoft Excel function sumif adds up cells that satisfy a condition: ... In Excel, the <source> defines arbitrary cells—Ax:Ay in the following examples. In SQL, the picking the rows is separate from the picking of the columns. The the group by and over clauses specify the rows. The column is explicitly used in the <condition> that is put into the case expression.
🌐
Vertabelo Academy
academy.vertabelo.com › course › standard-sql-functions › case-when › case-when-with-aggregates › case-when-sum
Learn SQL By Doing - Practice CASE WHEN with SUM in Queries Online
SELECT SUM(CASE WHEN scholarship IS TRUE THEN place_limit ELSE 0 END) AS scholarship_places, SUM(CASE WHEN scholarship IS FALSE THEN place_limit ELSE 0 END) AS no_scholarship_places FROM course;
Find elsewhere
🌐
Five
five.co › blog › sql-sum-with-case
SQL SUM with CASE: Practical Guide | Five
October 23, 2024 - SELECT region, SUM(CASE WHEN order_status = 'Completed' THEN CASE WHEN order_value > 1000 THEN order_value * 0.20 WHEN order_value > 500 THEN order_value * 0.15 ELSE order_value * 0.10 END ELSE 0 END) AS total_commission, COUNT(DISTINCT CASE WHEN order_status = 'Completed' AND order_value > 1000 THEN sales_rep_id END ) AS high_performing_reps FROM sales_orders GROUP BY region; -- Problematic query SELECT SUM(CASE WHEN amount > 1000 THEN amount END) AS high_value_sales -- NULL if no matches -- Fixed version SELECT SUM(CASE WHEN amount > 1000 THEN amount ELSE 0 -- Explicitly handle non-matching cases END) AS high_value_sales FROM sales;
🌐
YouTube
youtube.com › watch
Intermediate SQL Tutorial | CASE WHEN and SUM() + CASE WHEN - YouTube
This video covers the CASE WHEN statement in SQL, as well as how to use SUM() + CASE WHEN. We cover CASE WHEN syntax and common use cases.00:00:00 Introducti...
Published: September 27, 2023
🌐
SQL Server Tutorial
sqlservertutorial.net › home › sql server basics › sql server case
Pragmatic Guide to SQL Server CASE Expression
April 11, 2020 - SELECT CASE order_status WHEN 1 THEN 'Pending' WHEN 2 THEN 'Processing' WHEN 3 THEN 'Rejected' WHEN 4 THEN 'Completed' END AS order_status, COUNT(order_id) order_count FROM sales.orders WHERE YEAR(order_date) = 2018 GROUP BY order_status; Code language: SQL (Structured Query Language) (sql) ... SELECT SUM(CASE WHEN order_status = 1 THEN 1 ELSE 0 END) AS 'Pending', SUM(CASE WHEN order_status = 2 THEN 1 ELSE 0 END) AS 'Processing', SUM(CASE WHEN order_status = 3 THEN 1 ELSE 0 END) AS 'Rejected', SUM(CASE WHEN order_status = 4 THEN 1 ELSE 0 END) AS 'Completed', COUNT(*) AS Total FROM sales.orders WHERE YEAR(order_date) = 2018; Code language: SQL (Structured Query Language) (sql)
🌐
Microsoft Learn
learn.microsoft.com › en-us › answers › questions › 599592 › conditional-sum-syntax-are-these-two-methods-both
Conditional Sum Syntax Are these two methods both correct or do they calculate or return results differently? - Microsoft Q&A
October 21, 2021 - In the second method, when WS_Cost_Code = 1, the value of WS_Extended is returned, and when WS_Cost_Code <> 1, it returns 0. Then the returned values are summed. If you specify the GROUP BY WS_Cost_Code clause, the returned result is the same as in the first method. If not specified, only one value is returned. ... select case when No1 = 3 then SUM(No2) else 0 end m1 from t group by No1 select sum(case when No1=3 then No2 else 0 end ) m2 from t select case when No1 = 3 then SUM(No2) else 0 end m1 ,sum(case when No1=3 then No2 else 0 end ) m2 from t group by No1
🌐
SQLServerCentral
sqlservercentral.com › home › topics › using sum() in case statement / best practices
Using SUM() In CASE Statement / Best Practices – SQLServerCentral Forums
November 6, 2018 - SELECT fund.SourceName, fund.FundID, trans.InvestorID, fundDates.theDate AS CurrentDate, SUM(trans.Capital * (CASE WHEN batch.BatchGLDate <= fundDates.theDate AND batch.BatchStatus = 'Posted' THEN 1 ELSE 0 END)) AS CurrentValue FROM TransAlloc trans INNER JOIN Batch batch ON trans.BatchID = batch.BatchID INNER JOIN Fund fund ON batch.LEID = fund.FundID INNER JOIN FundDates fundDates ON fund.FundID = fundDates.FundID WHERE batch.batchStatus IN ( 'Posted', 'Held') AND batch.BatchGLDate <= fundDates.theDate GROUP BY fund.SourceName, fund.FundID, trans.InvestorID, fundDates.theDate
Top answer
1 of 1
1

To answer this question, I did the following (all of the code below is available on the fiddle here):

Tables - as per question.

Data - simulated.

INSERT INTO customer VALUES
(1, 'cust1', 'Sales'),
(2, 'cust2', 'Sales'),
(3, 'cust3', 'Sales'),
(4, 'cust4', 'Sales'),
(5, 'cust5', 'Sales');

and

INSERT INTO invoice VALUES
(1,  1, '2022-01-01', '2022-01-03',         NULL,         NULL,   1.0),
(2,  1, '2022-01-03', '2022-01-08',         NULL,         NULL,   1.0),
(3,  1, '2022-01-05', '2022-01-13',         NULL,         NULL,   1.0),

(4,  2, '2022-02-01', '2022-02-03',         NULL,         NULL,   2.0),
(5,  2, '2022-02-03', '2022-02-08',         NULL,         NULL,   2.0),
(6,  2, '2022-02-05', '2022-02-13',         NULL,         NULL,   2.0),


(7,  3, '2022-03-01',         NULL, '2022-03-07',         NULL,  3.0),
(8,  3, '2022-03-08',         NULL, '2022-03-14',         NULL,  3.4),
(9,  3, '2022-03-14',         NULL, '2022-03-21',         NULL,  3.4),

(10, 4, '2022-04-01', '2022-04-06', '2022-04-10', '2022-04-22',  4.0),  -- with 4, some refunded
(11, 4, '2022-04-02', '2022-04-07', '2022-04-12', '2022-04-25',  4.1),  -- some not!
(12, 4, '2022-04-03', '2022-04-09', '2022-04-16', '2022-04-28',  4.2),

(13, 4, '2022-04-20', '2022-04-27',         NULL,         NULL, 100.1),
(14, 4, '2022-04-21', '2022-04-29',         NULL,         NULL, 100.2);

The first query is "exploratory" - i.e. getting the required information together. Use is made of window functions - these are very powerful and are well worth getting to know - they will repay any effort spent on learning them many times over!

SELECT
  ROW_NUMBER() OVER (PARTITION BY c.id ORDER BY c.id, i.time_issued) AS rn,
  i.invoice_number AS invno, c.id AS cid, c.customer_name AS cname, c.dept AS cdept,
  i.time_issued AS idate, i.time_paid AS ipaid, 
  i.time_canceled AS icancel, 
  i.time_refunded AS irefund,
  LAST_VALUE(i.time_issued) OVER (PARTITION BY c.id ORDER BY c.id) AS l_inv_date,
  ROUND(COALESCE(i.total_price, 0), 2)   AS tot_price,
  ROUND(SUM(i.total_price) OVER (PARTITION By c.id ORDER BY c.id), 2) AS s_tot,
  ROUND(SUM(NULLIF(time_refunded IS NOT NULL, NULL) * total_price)
     OVER (PARTITION BY c.id ORDER BY c.id), 2) AS refund,

  ROUND(SUM(i.total_price) OVER (PARTITION By c.id ORDER BY c.id) -
  SUM(NULLIF(time_refunded IS NOT NULL, NULL) * total_price)
     OVER (PARTITION BY c.id ORDER BY c.id), 2) AS billed


FROM
  customer c
LEFT JOIN invoice i
  ON i.customer_id = c.id
ORDER BY cid, idate;

Result:

For the result, see the fiddle.

And then, we run the query:

SELECT
  cid, cname, inv_count, l_inv_date, s_tot, refund, valid_billed
FROM
(
  SELECT
    ROW_NUMBER() OVER (PARTITION BY c.id ORDER BY c.id, i.time_issued) AS rn,
    c.id AS cid, c.customer_name AS cname,
    
    COUNT(i.invoice_number) OVER (PARTITION BY c.id ORDER BY c.id) AS inv_count,
    
    LAST_VALUE(i.time_issued) OVER (PARTITION BY c.id ORDER BY c.id) AS l_inv_date,
    
    ROUND(COALESCE(SUM(i.total_price) OVER (PARTITION BY c.id ORDER BY c.id), 0), 2) AS s_tot,
    ROUND(COALESCE(SUM(NULLIF(time_refunded IS NOT NULL, NULL) * total_price)
      OVER (PARTITION BY c.id ORDER BY c.id), 0), 2) AS refund,

    ROUND(COALESCE(SUM(i.total_price) OVER (PARTITION By c.id ORDER BY c.id) -
      SUM(NULLIF(time_refunded IS NOT NULL, NULL) * total_price)
        OVER (PARTITION BY c.id ORDER BY c.id), 0), 2) AS valid_billed
FROM
  customer c
LEFT JOIN invoice i
  ON i.customer_id = c.id
) AS sub1
WHERE rn = 1
ORDER BY cid;

Result:

cid  cname  inv_count   l_inv_date  s_tot   refund  valid_billed
1    cust1          3   2022-01-05      3        0             3
2    cust2          3   2022-02-05      6        0             6
3    cust3          3   2022-03-14    9.8        0           9.8
4    cust4          5   2022-04-21  212.6     12.3         200.3
5    cust5          0         NULL      0        0             0
  • in future, when asking questions such as this, please include a fiddle with your tables and data. The usefulness of this is twofold - it creates a single source of truth for the question and it eliminates duplication of effort on behalf of those trying to help you.
🌐
Reddit
reddit.com › r/postgresql › sum, case when
r/PostgreSQL on Reddit: Sum, CASE WHEN
September 14, 2021 -

Hello everyone, I am facing an issue, I have a division in query. Something like rate = value/ total value (which is sum). It was working fine but I recently faced error of Zero division. So how can I overcome that? Currently, what I am thinking of doing to avoid 0 in denominator is to use CASE WHEN.

SELECT value/SUM( CASE WHEN total_value = 0 THEN 1 ELSE total_value END) FROM.....

Is it okay to do like this or is there any other approach?

TIA.

🌐
Stack Overflow
stackoverflow.com › questions › 66042606 › sumcase-when-with-condition-of-another-aggregate-function
sql - SUM(CASE WHEN) with condition of another aggregate function - Stack Overflow
select scan_date, Location, sum(case when scan_code EQ '01' then 1 else 0 end) as Scan01, sum(case when num_id_01 > 0 and scan_code EQ '02' then 1 else 0 end) as Scan02 from (select s.*, sum(case when scan_code EQ '01' then 1 else 0 end) over (partition by id, scan_date) as num_id_01 from ScanDB s where s.scan_date between '?From' and '?To' ) s group by scan_date, Location;
🌐
Reddit
reddit.com › r/netsuite › sum case when
r/Netsuite on Reddit: Sum Case When
August 23, 2022 -

Trying to figure out how to sum a case when formula for multiple items -

CASE WHEN {item}

= 'CITL' THEN {amount}

= 'CITV' THEN {amount}

= 'CRDD' THEN {amount}

= 'DETN' THEN {amount}

= 'DLVAP' THEN {amount}

= 'DRASF' THEN {amount}

= 'DRYR' THEN {amount}

= 'LAYVR' THEN {amount}

= 'PGUAR' THEN {amount}

= 'LUMP' THEN {amount}

= 'RCOG' THEN {amount}

= 'RDEL' THEN {amount}

ELSE 0

END

This gets me an error, not sure if I messed this up.