MySQL:将值检索到不同的列中

Posted

技术标签:

【中文标题】MySQL:将值检索到不同的列中【英文标题】:MySQL: Retrieving values into different columns 【发布时间】:2015-02-13 07:48:08 【问题描述】:

请看下面的代码。

SELECT Transactions.`idTransactions`,
Transactions.`Transaction_TimeStamp`,
Transactions.`idPortfolio`,
CASE  when Transactions.`Transaction_Amount`< 0  THEN END AS "Encashments"  ELSE END AS "Additions" ,
Portfolio.Activation 
FROM Transactions 
INNER JOIN Portfolio ON Transactions.idPortfolio = Portfolio.idPortfolio 
WHERE Transactions.idPortfolio=1
ORDER BY `Transaction_TimeStamp` DESC

这里,如果Transactions.Transaction_Amount >0,那么我需要在“Additions”列中显示该值,否则在“Encashment”列中显示。但是我的代码产生如下错误。

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your mysql server version for the right syntax to use near 'AS "Encashments"  ELSE END AS "Additions" ,
Portfolio.Activation 
FROM Transacti' at line 4 

请问我该如何解决这个问题?

【问题讨论】:

【参考方案1】:

如果您想要 2 个不同的列,则使用两种情况

SELECT Transactions.`idTransactions`,
       Transactions.`Transaction_TimeStamp`,
       Transactions.`idPortfolio`,
       CASE when Transactions.`Transaction_Amount` <= 0 
            THEN  (Transaction_Amount*-1)
       END AS Encashments,
       CASE when Transactions.`Transaction_Amount` > 0 
            THEN Transaction_Amount
       END AS Additions,
       Portfolio.Activation 
FROM Transactions 
INNER JOIN Portfolio ON Transactions.idPortfolio = Portfolio.idPortfolio 
WHERE Transactions.idPortfolio=1
ORDER BY `Transaction_TimeStamp` DESC

【讨论】:

我遇到错误,你能合并完整的代码吗? abs(Transaction_Amount) 或只是 Transaction_Amount*-1 感谢您的帮助,非常感谢。 您好,代码有问题。它将兑现显示为加法,反之亦然... 然后互换名称【参考方案2】:

您应该将 SQL 用作:

SELECT Transactions.`idTransactions`,
Transactions.`Transaction_TimeStamp`,
Transactions.`idPortfolio`,
CASE  when Transactions.`Transaction_Amount`< 0  THEN "Encashments"  ELSE "Additions" END AS Type,
Portfolio.Activation 
FROM Transactions 
INNER JOIN Portfolio ON Transactions.idPortfolio = Portfolio.idPortfolio 
WHERE Transactions.idPortfolio=1
ORDER BY `Transaction_TimeStamp` DESC

then 语法错误的情况。你可以参考here

【讨论】:

【参考方案3】:

你的案子没有结果。

CASE  when Transactions.`Transaction_Amount`< 0  THEN something_missing_here END AS

【讨论】:

以上是关于MySQL:将值检索到不同的列中的主要内容,如果未能解决你的问题,请参考以下文章

根据R中的查找值将值分配给不同的列

如果值不存在,将值插入 MySQL 表?

Sequelize 不会将值插入到新添加的列中

MYSQL:如何在 mysql 中将整行从一个表复制到另一个表,而第二个表有一个额外的列?

C# MySQL 从与另一个匹配的列中检索值

将值动态添加到 MS 访问数据库并使用变量检索它们