How can I group by in sql on a field from other table. Here’s my code
select
sum(a.trans_amount), (
select
ledger_name
from
ledger_master
where
ledger_master.ledger_code = transaction_ledger.ledger_code
) as ledger_name,
ledger_code
from
transaction_ledger
where
ledger_parent = 'Sundry Debtors'
group by
ledger_code,
ledger_name
Why not join the results and then grouping by?
Your Ledger_Master and Transaction_Ledger has a related column “Ledger_Code” which you have used in the example query you have provided.
Keeping that in mind, you can proceed to group by the required fields after a join on those two fields of the two tables.
Luckily, the select list you want (Name & Code) can be used to group as well – thus not violating the grouping rules.