MySQL查询与其他行上的减法

时间:2017-05-22 04:02:09

标签: mysql database

MySQL查询:

SELECT SUM(t.transactionAmt) as transactionAmt, c.categoryType, MONTH(str_to_date(t.transactionDate, '%d/%m/%Y')) as transactionMonth,  YEAR(str_to_date(t.transactionDate, '%d/%m/%Y')) as transactionYear
FROM transaction_db t INNER JOIN category_db c
ON t.categoryID = c.categoryID
WHERE t.accountID = '12'
GROUP BY c.categoryType, MONTH(str_to_date(t.transactionDate, '%d/%m/%Y'))
ORDER BY MONTH(str_to_date(t.transactionDate, '%d/%m/%Y')) DESC

这是输出:

有没有办法以这样的方式查询它,如果有来自同一个transactionMonth的行,我将带有categoryType 0的行减去带有categoryType 1的行?

例如,对于第5个月,我采用2233减去464得到结果。

提前致谢!

1 个答案:

答案 0 :(得分:0)

您可以从查询中创建一个视图(有关详细信息,请参阅Create VIEW Syntax),该视图将在子查询中使用:

SELECT 
  cat1.transactionAmt - cat2.transactionAmt AS transactionDiff
FROM 
  (SELECT * FROM MyView WHERE categoryType = 0) AS cat1 
  JOIN
  (SELECT * FROM  MyView AS cat1 WHERE categoryType = 1) AS cat2
  USING(transactionMonth);

或尝试使用Control Flow Functions。例如:

SELECT 
  SUM(IF(c.categoryType=0, t.transactionAmt, -t.transactionAmt)) as transactionAmt, 
  MONTH(str_to_date(t.transactionDate, '%d/%m/%Y')) as transactionMonth,  
  YEAR(str_to_date(t.transactionDate, '%d/%m/%Y')) as transactionYear
FROM 
  transaction_db t INNER JOIN category_db c
  ON t.categoryID = c.categoryID
WHERE t.accountID = '12'
GROUP BY MONTH(str_to_date(t.transactionDate, '%d/%m/%Y'))
ORDER BY MONTH(str_to_date(t.transactionDate, '%d/%m/%Y')) DESC