Home > Database > Mysql Tutorial > How to Filter Cash Values by Date in SQL for Total Summation?

How to Filter Cash Values by Date in SQL for Total Summation?

Mary-Kate Olsen
Release: 2025-01-05 03:11:43
Original
474 people have browsed it

How to Filter Cash Values by Date in SQL for Total Summation?

Totaling Cash Values with Date Filtering in SQL

As you mentioned, you have a SQL statement that calculates the total cash for each unique transaction ID using the following line:

select sum(cash) from Table a where a.branch = p.branch and a.transID = p.transID) TotalCash
Copy after login

To modify this statement to only total cash values that have a value date within the last month, you can update it in the following way:

select SUM(CASE WHEN ValueDate > @startMonthDate THEN cash ELSE 0 END)
from Table a where a.branch = p.branch and a.transID = p.transID) TotalMonthCash
Copy after login

Explanation:

  • CASE WHEN...THEN...ELSE...END: This is the searched CASE expression syntax, which compares a Boolean expression (in this case, ValueDate > @startMonthDate) to a set of results. If the Boolean expression is true, it returns the cash value; otherwise, it returns 0.
  • SUM(): This function is used to calculate the total of the cash values that meet the date filtering criteria.

Performance Optimization:

As a side note, if the performance of your query becomes an issue, consider rewriting it using a JOIN and GROUP BY instead of a dependent subquery. This can potentially improve the execution time.

The above is the detailed content of How to Filter Cash Values by Date in SQL for Total Summation?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template