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
Mary-Kate OlsenOriginal
2024-12-31 07:55:10877browse

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;

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

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!

Statement:
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