Account_IDが両方のテーブルで一意であるかどうかによって、2つの方法があります。 (ACCOUNT_IDが各テーブルに一意である場合)より高速な方法:
SELECT A.*, N16.Amount as Amount_2016
, N17.Amount as Amount_2017
, N18.Amount as Amount_2018
, N19.Amount as Amount_2019
FROM ACCOUNTS A
LEFT JOIN NET_PROCEEDS N16 ON N16.Account_ID = A.Account_ID AND N16.Fiscal_Year = '2016'
LEFT JOIN NET_PROCEEDS N17 ON N17.Account_ID = A.Account_ID AND N17.Fiscal_Year = '2017'
LEFT JOIN NET_PROCEEDS N18 ON N18.Account_ID = A.Account_ID AND N18.Fiscal_Year = '2018'
LEFT JOIN NET_PROCEEDS N19 ON N19.Account_ID = A.Account_ID AND N19.Fiscal_Year = '2019'
安全な方法(ACCOUNT_IDがない場合/各テーブルに一意ではないかもしれない):
SELECT A.*, (SELECT SUM(N16.Amount) FROM NET_PROCEEDS N16 ON N16.Account_ID = A.Account_ID AND N16.Fiscal_Year = '2016') as Amount_2016
, (SELECT SUM(N17.Amount) FROM NET_PROCEEDS N17 ON N17.Account_ID = A.Account_ID AND N17.Fiscal_Year = '2017') as Amount_2017
, (SELECT SUM(N18.Amount) FROM NET_PROCEEDS N18 ON N18.Account_ID = A.Account_ID AND N18.Fiscal_Year = '2018') as Amount_2018
, (SELECT SUM(N19.Amount) FROM NET_PROCEEDS N19 ON N19.Account_ID = A.Account_ID AND N19.Fiscal_Year = '2019') as Amount_2019
FROM ACCOUNTS A
あなたが使用している場合最初にAccount_IDが一意でないときは、Account_IDの複製インスタンスごとに複数の行が作成され、SUMやCOUNTなどが混乱します。
ありがとうございますが、net_proceedsテーブルにaccount_IDが多数ある可能性があります。 – Dhenn
こんにちは、うん、それで、なぜあなたは2番目のクエリ – tomb