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.
| Author |
Topic |
|
CaptainSensible
Starting Member
4 Posts |
Posted - 2007-03-14 : 12:40:10
|
| Hi AllI need to count records from a joined pair of tables.It needs to be a total count (i.e. a single numeric result) of entries from Table1 that exclude a given user that I supply as a parameter, and also exclude any entries where there are no corresponding records in the second joined table. The tables are joined on the ID fields.I can see a way of getting the count using nested queries, but is there a neater way?Table1ID USER-- ----1 X2 Y3 Z4 Y5 Y6 XTable2ID DATA-- ----1 text12 text21 text35 text44 text56 text62 text7If supply the following user names in three seperate queries I would expect:-X to give the result 3Y to give the result 2Z to give the result 5Thanks in advance for any help.James |
|
|
snSQL
Master Smack Fu Yak Hacker
1837 Posts |
Posted - 2007-03-14 : 13:22:07
|
| Your sample data and results don't seem to tie up, exactly how do you get to X to give the result 3Y to give the result 2Z to give the result 5from the data you gave? |
 |
|
|
snSQL
Master Smack Fu Yak Hacker
1837 Posts |
Posted - 2007-03-14 : 13:37:08
|
Maybe I figured it outSELECT count(distinct Table2.ID)FROM Table1INNER JOIN Table2 ON Table1.ID = Table2.IDWHERE Table1.ID <> @UserID |
 |
|
|
CaptainSensible
Starting Member
4 Posts |
Posted - 2007-03-14 : 13:40:31
|
| OKIf I supply user X then I get ID numbers 2,3,4 & 5 from the first table. Of, those ID 3 has no corresponding records in the second table so gets ignored. That leaves a total count of 3.Y gets 1,3 & 6 from the first table. Again 3 has no records in the second table which gives 2Z gets 1,2,4,5 & 6 from the first table. All have records in the second table so nothing gets taken out giving the end result of 5.Hope that explains it a bit better.CheersJames. |
 |
|
|
CaptainSensible
Starting Member
4 Posts |
Posted - 2007-03-14 : 13:43:12
|
| Oops, seem to have crossed over posts there.I'll give it a try.James. |
 |
|
|
CaptainSensible
Starting Member
4 Posts |
Posted - 2007-03-16 : 06:23:11
|
| Brilliant, it works.Just had to change "Table1.ID" in the last line to "Table1.USER"Also much faster than my original nested queries.Thanks for the help snSQL.James. |
 |
|
|
|
|
|
|
|