Link to home
Start Free TrialLog in
Avatar of fwstealer
fwstealerFlag for United States of America

asked on

join results as one column

how do i return a result set back as one column?

select Distinct((LEFT(RIGHT(GLTran.Sub, 20), 3))) AS SubAcct , Account.Descr
from GLTran
INNER JOIN Account ON GLTran.Acct = Account.Acct
where GLTran.Acct >= '40000' AND GLTran.Acct < '50000' order by SubAcct asc

SubAccount     Descr
000                    (Gain)/Loss Extin of Debt


want 1 col instead of 2
000 - Gain/Loss Extin of Debt
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

CAST the account number (assuming it's numeric) as a varchar, then you can concatenate the varchar number and description into one column

select CAST(Distinct((LEFT(RIGHT(GLTran.Sub, 20), 3))) AS varchar(max)) + ' - ' + Account.Descr as account
from GLTran
INNER JOIN Account ON GLTran.Acct = Account.Acct
where GLTran.Acct >= '40000' AND GLTran.Acct < '50000' order by SubAcct asc
Avatar of fwstealer

ASKER

got an error:

Incorrect syntax near the keyword 'as'.

CAST(Distinct((LEFT(RIGHT(GLTran.Sub, 20), 3))) as varchar(max))
If this value is always three characters than replace varchar(max) with char(3).

This may also work..

select Distinct(CAST(LEFT(RIGHT(GLTran.Sub, 20), 3) AS varchar(max))) + ' - ' + Account.Descr as account
from GLTran
INNER JOIN Account ON GLTran.Acct = Account.Acct
where GLTran.Acct >= '40000' AND GLTran.Acct < '50000' order by SubAcct asc

Since I don't have access to your data source there's no way I can validate if Distinct((LEFT(RIGHT(GLTran.Sub, 20), 3))) is correct, so you're on your own on that one.
minor change:

select Distinct(CAST(LEFT(RIGHT(GLTran.Sub, 20), 3) AS varchar(max))) + ' - ' + Account.Descr as account
from GLTran
INNER JOIN Account ON GLTran.Acct = Account.Acct
where GLTran.Acct >= '40000' AND GLTran.Acct < '50000' order by GLTran.Sub asc

error:
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
ASKER CERTIFIED SOLUTION
Avatar of Jim Horn
Jim Horn
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
order by 1 worked!
Thanks for the grade.  Good luck with your project.  -Jim

>order by 1 worked!
If you're SELECTing a lot of calculations, you can ORDER BY the position of the column (1, 2, 3, ...) instead of having to re-calculate.