Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

SQL Subquery Count Problem 1

Status
Not open for further replies.

waiterm

Programmer
May 17, 2004
236
GB
Hi,

I'm trying to join two tables, whereby the first table has unique records, the second table then has multiple records assigned against the primary key of the first table.

Basically I'm looking for a query which lists the top 20 records from the first table with an extra field stating the number of records associated to it in the second field.

i.e.

Table 1
T1PK
1 Field1_1 Field1_2 Field1_3
2 Field2_1 Field2_2 Field2_3
3 Field3_1 Field3_2 Field3_3

Table 2
T2PK T1PK
1 Field1_1 1
2 Field2_1 1
3 Field3_1 3

Results
T1PK Count
1 Field1_1 Field1_2 Field1_3 2
2 Field2_1 Field2_2 Field2_3 0
3 Field3_1 Field3_2 Field3_3 1

Having racked my brains for ages and got nowhere any help would be gratefully appreciated.


Rob Waite
 
Code:
select top 20
       T1PK
     , Fieldx_1  
     , Fieldx_2  
     , Fieldx_3
     , ( select count(*)
           from Table2
          where T1PK = Table1.T1PK )
              as [Count]
  from Table1
order
    by something

r937.com | rudy.ca
 
Hi,

Many thanks for your reply, have tried that, it's certainly progress, however it gives the total number of records for the entire second table as opposed to the total number of records associated with each record in table 1.

Regards



Rob Waite
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top