本文介绍了MySQL中的Case语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为tbl_transaction"的数据库表,其定义如下:

I have a database table called 'tbl_transaction' with the following definition:

id INT(11) Primary Key
action_type ENUM('Expense', 'Income')
action_heading VARCHAR (255)
action_amount FLOAT

我想生成两列:Income AmtExpense Amt.

I would like to generate two columns: Income Amt and Expense Amt.

是否可以仅使用 SQL 查询有条件地填充列,以便输出显示在正确的列中,具体取决于它是费用项目还是收入项目?

Is it possible to populate the columns conditionally, using only a SQL Query, such that the output appears in the correct column, depending on whether it is an Expense item or an Income item?

例如:

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

我使用 MySQL 作为数据库.我正在尝试使用 CASE 语句来完成此操作.

I'm using MySQL as the database. I'm trying to use the CASE statement to accomplish this.

干杯!

推荐答案

是的,像这样:

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;

正如其他答案所指出的那样,MySQL 还具有 IF() 函数来使用较少冗长的语法来执行此操作.我通常会尽量避免这种情况,因为它是 SQL 的特定于 MySQL 的扩展,其他地方通常不支持.CASE 是标准 SQL,并且在不同的数据库引擎之间具有更高的可移植性,我更喜欢尽可能编写可移植的查询,仅在可移植的替代方案相当时才使用特定于引擎的扩展em> 较慢或不太方便.


As other answers have pointed out, MySQL also has the IF() function to do this using less verbose syntax. I generally try to avoid this because it is a MySQL-specific extension to SQL that isn't generally supported elsewhere. CASE is standard SQL and is much more portable across different database engines, and I prefer to write portable queries as much as possible, only using engine-specific extensions when the portable alternative is considerably slower or less convenient.

这篇关于MySQL中的Case语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 19:44