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
 getting total records from first table

Author  Topic 

ramyasre
Starting Member

16 Posts

Posted - 2011-04-28 : 00:47:25
Hi,

The following are two tables

LocationCode FormCode
________________________

10201 op008
10201 op009
10201 op010
10201 ip003
10201 ip005
10202 op008
10202 op010

Another Table is

FormCode Score LocationCode
___________________________________
op008 11 10201
op010 20 10201
op008 4 10201
op009 3 10201
op008 7 10201

Now I want output as follows

FormCode TotalForms LocationCode
________________________________________

op008 3 10201
op009 1 10201
op010 1 10201
ip003 0 10201
ip005 0 10201
op008 0 10202
op010 0 10202

webfred
Master Smack Fu Yak Hacker

8781 Posts

Posted - 2011-04-28 : 01:13:30
Can you please explain the rule to get that result?


No, you're never too old to Yak'n'Roll if you're too young to die.
Go to Top of Page

vaibhavktiwari83
Aged Yak Warrior

843 Posts

Posted - 2011-04-28 : 02:23:04
This is what I understood your rule -

CREATE TABLE tbl1 ( LocationCode INT, FormCode VARCHAR(10) )

INSERT INTO tbl1
SELECT '10201','op008'
UNION ALL
SELECT '10201','op009'
UNION ALL
SELECT '10201','op010'
UNION ALL
SELECT '10201','ip003'
UNION ALL
SELECT '10201','ip005'
UNION ALL
SELECT '10202','op008'
UNION ALL
SELECT '10202','op010'

CREATE TABLE tbl2 ( FormCode VARCHAR(10), Score INT, LocationCode INT )

INSERT INTO tbl2

SELECT 'op008','11','10201'
UNION ALL
SELECT 'op010','20','10201'
UNION ALL
SELECT 'op008','4','10201'
UNION ALL
SELECT 'op009','3','10201'
UNION ALL
SELECT 'op008','7','10201'

SELECT a.FormCode, COUNT(b.FormCode) TotalForms, a.LocationCode FROM tbl1 a
LEFT JOIN tbl2 b ON a.FormCode = b.FormCode AND a.LocationCode = b.LocationCode
GROUP BY a.FormCode, a.LocationCode
ORDER BY TotalForms DESC


Vaibhav T

If I cant go back, I want to go fast...
Go to Top of Page

ramyasre
Starting Member

16 Posts

Posted - 2011-04-28 : 02:35:59
Thank q
Go to Top of Page

vaibhavktiwari83
Aged Yak Warrior

843 Posts

Posted - 2011-04-28 : 02:46:46
Welcome

Vaibhav T

If I cant go back, I want to go fast...
Go to Top of Page
   

- Advertisement -