Case statement in MySQL(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 Amt
和 Expense 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语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:MySQL中的Case语句


- 更改自动增量起始编号? 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- SQL 临时表问题 2022-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01