dbTalk Databases Forums  

Count from detail table

comp.databases.ms-sqlserver comp.databases.ms-sqlserver


Discuss Count from detail table in the comp.databases.ms-sqlserver forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
Cacho
 
Posts: n/a

Default Count from detail table - 02-20-2008 , 10:57 AM







Hi

I've two tables

TableA
id
name

TableB
id
tableA_id
desc
oper


As you can see tableA is a master and tableB is a detail table where
we can have many records for each related tableA record.

I need to get all records for tableA with a count on some oper of
tableB.

I suppose I can got it with a join or a subselect but I don't use SQL
often so I'm getting crazy with this stupid query...

Could somebody help ?

Thanks in advance

C






Reply With Quote
  #2  
Old   
Plamen Ratchev
 
Posts: n/a

Default Re: Count from detail table - 02-20-2008 , 11:17 AM






It is a good practice to name related columns with the same name across
tables.

Here is a query that will give you the counts for selected oper:

SELECT A.id, A.name, COUNT(B.oper) AS oper_cnt
FROM TableA AS A
LEFT OUTER JOIN TableB AS B
ON A.id = B.tablea_id
AND B.oper = 'a'
GROUP BY A.id, A.name

HTH,

Plamen Ratchev
http://www.SQLStudio.com


Reply With Quote
  #3  
Old   
Cacho
 
Posts: n/a

Default Re: Count from detail table - 02-21-2008 , 02:41 AM



On 20 feb, 18:17, "Plamen Ratchev" <Pla... (AT) SQLStudio (DOT) com> wrote:
Quote:
It is a good practice to name related columns with the same name across
tables.

Here is a query that will give you the counts for selected oper:

SELECT A.id, A.name, COUNT(B.oper) AS oper_cnt
FROM TableA AS A
LEFT OUTER JOIN TableB AS B
* ON A.id = B.tablea_id
*AND B.oper = 'a'
GROUP BY A.id, A.name

HTH,

Plamen Ratchevhttp://www.SQLStudio.com
Thank you !

C


Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.