MySQL中相关子查询的总和 - 使用相同的表

时间:2012-03-28 14:55:55

标签: mysql sql

我有一张桌子,每个月的不同日期都有多笔付款。我希望查询为每个单独的付款返回一行,并在同一行中返回该月/年的所有付款的总和。

我的表结构是:

   tbl_or_Distri
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `investment_id` int(11) NOT NULL,
  `inv_distri_id` int(11) NOT NULL,
  `trade_date` datetime NOT NULL,
  `pay_date` datetime NOT NULL,
  `amount` double NOT NULL,
  `perc_return` double NOT NULL,
   PRIMARY KEY (`id`),

我目前的内部查询是:

SELECT
 `investment_id`,
 SUM(`perc_return`) as perc_return,
 SUM(`capital_return`) as capital_return,
 SUM(amount) as TotalAmount, 
 CONCAT(MONTH(pay_date), " ", YEAR(pay_date)) as short_date,
 MONTH(pay_date) as pay_month,
 YEAR(pay_date) as pay_year
FROM `tbl_or_distri`
WHERE investment_id=29
GROUP BY YEAR(pay_date), MONTH(pay_date)

sum(amount),sum(perc_return)和short_date是我需要在主外部查询的每一行中返回的3条记录。外部查询是:

SELECT
 `investment_id`,
  amount,
  pay_date
FROM `tbl_or_distri`
WHERE investment_id=29

如何将这两个查询合并为一个?在保持良好表现的同时 谢谢!

2 个答案:

答案 0 :(得分:0)

你可以为你的内部查询创建一个视图。

CREATE VIEW NameYourView AS
SELECT
 `investment_id`,
 SUM(`perc_return`) as perc_return,
 SUM(`capital_return`) as capital_return,
 SUM(amount) as TotalAmount, 
 CONCAT(MONTH(pay_date), " ", YEAR(pay_date)) as short_date,
 MONTH(pay_date) as pay_month,
 YEAR(pay_date) as pay_year
FROM `tbl_or_distri`
GROUP BY YEAR(pay_date), MONTH(pay_date)

然后在外部查询中使用该视图。

SELECT t.investment_id, t.amount, t.pay_date, v.*
FROM `tbl_or_distri` t
inner join NameYourView v on v.investment_id = t.investment_id
WHERE t.investment_id=29

我不知道它对性能的影响,但肯定会有效。

答案 1 :(得分:0)

您是否需要每行中的SUM或者您是否只需要在同一查询中使用该信息?如果是后者,那么WITH ROLLUP可能会为你做到这一点

SELECT
  `id`, 
  CONCAT(MONTH(pay_date), " ", YEAR(pay_date)) as short_date,
  MONTH(pay_date) as pay_month,
  YEAR(pay_date) as pay_year,
  SUM(`perc_return`) as perc_return,
  SUM(`capital_return`) as capital_return,
  SUM(amount) as TotalAmount
FROM `tbl_or_distri`
WHERE investment_id=29
GROUP BY pay_year, pay_month WITH ROLLUP