How to display values selected according to different criteria?

Started by jeromebunker, Sep 29, 2022, 01:24 AM

Previous topic - Next topic

jeromebunkerTopic starter

To generate a report from the database, I require specific information and formatting. Specifically, each line of the report must contain the division, year_month, and money fields. Additionally, the report should only consider records where the article field is either "revenue" or "expenses." In the case of revenue, there will be only one record, whereas there may be multiple expenses entries.

It's important to note that not every month may have revenue or expenses entries. To complete the desired report, I must also include the difference between the revenue and expenses columns for each month.
  •  

jahanzaibkhan

The provided code is an example of a SQL query used to generate a report from a database. To achieve the desired results, the query uses conditional statements to filter the records by their article field values, such as "revenue" or "expenses."

The resulting report contains the department and year_month fields, along with their corresponding revenue and expenses values. Additionally, the query calculates the difference between the revenue and expenses columns for each month.

It's worth noting that this code is specific to the "mytable" database and may require adaptation for other databases.

SELECT department, year_month,
     SUM(CASE WHEN item='revenue' THEN money ELSE 0 END) AS revenue,
     SUM(CASE WHEN item='expenses' THEN money ELSE 0 END) AS expenses,
     SUM(CASE WHEN item='revenue' THEN money ELSE -money END) AS difference
   FROM mytable
   GROUP BY division, year_month
  •