2014-01-13 57 views
2

我不知道该怎么称呼它,我试图解释它。MYSQL内部连接错误 - 'where子句'中的未知列'm.account_no'

我有两个表:

1.会员

enter image description here

2. share_trx_history

enter image description here

一个成员可以有多个共享的记录,我有以下结构 来显示它(总借记卡,信用卡,平衡给定年份的开口)

+-----------+------+-------+--------+---------+--------+ 
|account_no | name | debit | credit | balance | opening| 
+-----------+------+-------+--------+---------+--------+ 

我都试过,但它失败:

SELECT m.account_no, m.name, share.* 
FROM `member` AS m 
INNER JOIN (
    SELECT sth.account_no AS sth_account_no, SUM(sth.debit) AS sth_debit, SUM(sth.credit) AS sth_credit,(
    SELECT sth2.balance 
    FROM `share_trx_history` AS sth2 
    WHERE sth2.account_no=m.account_no 
    ORDER BY sth2.share_issue_date ASC 
    LIMIT 0,1 
) AS sth_balance, 
    (SELECT balance 
     FROM `share_trx_history` AS sth3 
     WHERE year(sth3.share_issue_date) <2014 AND sth3.account_no=m.account_no 
     ORDER BY sth3.share_issue_date DESC 
     LIMIT 0 , 1) AS sth_opening 
FROM `share_trx_history` AS sth 
WHERE sth.share_issue_date >= DATE_SUB(NOW(), INTERVAL 1 Year) 
AND sth.account_no=m.account_no) AS share 
ON share.sth_account_no = m.account_no 

捐赠以下错误:

Unknown column 'm.account_no' in 'where clause' 

有没有简单的方法来完成它?

我的查询出了什么问题?

谢谢

更新:

balance = (total debit + total dividend) - (total credit)

请检查opening = previous year balance

+0

你可以分享你的表结构,通过'http:/ /平方lfiddle.com /'? – ursitesion

+0

好的我在sqlfiddle上分享它 –

回答

1

试试这个:

SELECT m.account_no, m.name, SUM(sth.debit) AS sth_debit, SUM(sth.credit) AS sth_credit, 
     MAX(CASE share_issue_date WHEN start_date THEN balance ELSE 0 END) AS sth_balance, 
     MAX(CASE share_issue_date WHEN opening_date THEN balance ELSE 0 END) AS sth_opening 
FROM `member` AS m 
INNER JOIN share_trx_history AS sth ON m.account_no = sth.account_no 
INNER JOIN (SELECT account_no, MIN(share_issue_date) start_date, MAX(share_issue_date) opening_date 
      FROM share_trx_history WHERE YEAR(share_issue_date) <2014 GROUP BY account_no 
     ) AS A ON sth.account_no = A.account_no AND share_issue_date IN (start_date, opening_date) 
WHERE sth.share_issue_date >= DATE_SUB(NOW(), INTERVAL 1 YEAR) 
GROUP BY m.account_no 
+0

谢谢@Saharsh Shah求助,但'balance =(debit + devidend) - (credit)',请检查'opening =上一年的余额',您的答案非常有帮助 –

+0

@ SunilKumar什么股息是指? –

+0

@Saharsha等待先生的某种兴趣,只需将其视为一个列以添加到借记卡 –