我有一個表,每月有不同日期發生多次付款。我希望查詢爲每個單獨的付款返回一行,並在同一行中返回該月/年的所有付款的SUM。總和在MySQL中的相關子查詢 - 使用相同的表
我的表結構是:
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)
總和(量),和(perc_return),和SHORT_DATE是3條記錄我需要返回主外部查詢的每一行。外部查詢是:
SELECT
`investment_id`,
amount,
pay_date
FROM `tbl_or_distri`
WHERE investment_id=29
如何將這兩個查詢合併爲一個?保持良好的表現? 謝謝!
你試過'join'嗎? – safarov 2012-03-28 14:58:03