Home > Database > Mysql Tutorial > How to Populate Conditional Columns in MySQL Using CASE Statements?

How to Populate Conditional Columns in MySQL Using CASE Statements?

Mary-Kate Olsen
Release: 2024-12-31 07:55:10
Original
860 people have browsed it

How to Populate Conditional Columns in MySQL Using CASE Statements?

Case Statement for Conditional Column Population in MySQL

In the context of the 'tbl_transaction' table with columns 'id,' 'action_type,' 'action_heading,' and 'action_amount,' it is possible to generate desired result columns 'Income Amt' and 'Expense Amt' using a SQL query that populates these columns conditionally.

The query leverages the CASE statement's ability to evaluate the value of 'action_type' and assign the corresponding 'action_amount' to either the 'income_amt' or 'expense_amt' column.

SELECT
    id,
    action_heading,
    CASE
        WHEN action_type = 'Income' THEN action_amount
        ELSE NULL
    END AS income_amt,
    CASE
        WHEN action_type = 'Expense' THEN action_amount
        ELSE NULL
    END AS expense_amt
FROM tbl_transaction;
Copy after login

The result will be columns 'income_amt' and 'expense_amt' correctly populated with amounts based on the 'Income' or 'Expense' value in 'action_type.'

ID        Heading         Income Amt       Expense Amt
1         ABC             1000             -
2         XYZ             -                2000
Copy after login

The above is the detailed content of How to Populate Conditional Columns in MySQL Using CASE Statements?. 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