Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 Joining tables

Author  Topic 

Stan1978
Starting Member

31 Posts

Posted - 2011-07-11 : 11:07:37
SELECT
dbo.Trans.AccountID,
Sum(dbo.Trans.DeltaCash),
Count(dbo.Trans.DeltaCash)

FROM
dbo.Trans

WHERE
dbo.Trans.TransId BETWEEN '201107' AND '201107' AND
dbo.Trans.TransType = 'DEPOSIT'
GROUP BY
dbo.Trans.AccountID



I use this query to return accounts ids, deposit amount and number of deposits.

I have a 2nd table that i need to retrieve account information from e.g. Country, City. I am struggling because this table is structured . . .

Accid Field Value
1 Country UK
1 City London
2 City Barcelona
2 Country Spain


I am not sure how to return . .

Accid Deposit amount Number of deposits Country City


I hope I have given a clear enough explanation.
Thank you in advance for any help.

X002548
Not Just a Number

15586 Posts

Posted - 2011-07-11 : 12:54:49
Join to the table twice

Poor Data model though

Brett

8-)

Hint: Want your questions answered fast? Follow the direction in this link
http://weblogs.sqlteam.com/brettk/archive/2005/05/25/5276.aspx


Want to help yourself?

http://msdn.microsoft.com/en-us/library/ms130214.aspx

http://weblogs.sqlteam.com/brettk/

http://brettkaiser.blogspot.com/


Go to Top of Page

Stan1978
Starting Member

31 Posts

Posted - 2011-07-11 : 13:21:59
Thanks for the help, yeah I'm not happy with the data model I inherited it.

Sorry to be a pain (but I havent written SQL for 8 years) what syntax would you write to join the tables twice?
Go to Top of Page

mohdowais
Sheikh of Yak Knowledge

1456 Posts

Posted - 2011-07-11 : 13:31:01
A poor data model, indeed, as Brett says, which means the solution will be a little ugly.

There are actually a couple of ways of doing it, you can either join twice as suggested or use subqueries. Here's an example of the latter:


SELECT
dbo.Trans.AccountID,
Sum(dbo.Trans.DeltaCash),
Count(dbo.Trans.DeltaCash),
(SELECT Value FROM table2 t2 WHERE t2.Accid = trans.Accid AND Field = 'Country') AS Country,
(SELECT Value FROM table2 t2 WHERE t2.Accid = trans.Accid AND Field = 'City') AS City

FROM
dbo.Trans

WHERE
dbo.Trans.TransId BETWEEN '201107' AND '201107' AND
dbo.Trans.TransType = 'DEPOSIT'
GROUP BY
dbo.Trans.AccountID


P.S. @Brett, how are ya, mate?! Long time no see! Good to see you're still around.

OS
Go to Top of Page

Stan1978
Starting Member

31 Posts

Posted - 2011-07-12 : 03:28:30
Cheers guys works as expected.

Thanks for the quick (and correct) response really helped me out.
Go to Top of Page
   

- Advertisement -