Groups | Blog | Home
all groups > sql server (alternate) > march 2004 >

sql server (alternate) : Simple SQL - im stuck!!!



Gary W
3/18/2004 9:12:30 PM
Hello,

I am stuck on what is probably a very easy select query.
The query is:

Select Count(*), Distinct PID, ID, Name
From Table 1
Group By PID

I get:

| Count | PID | ID | Name |
--------------------------------------------------------
| 130 | GGT | 50 | Andy |
| 60 | AAM | 51 | Graeme |
| 360 | RGG | 52 | John |



Now, there are 130 records with a PID of GGT. Why has "Andy" been returned
in the row? There is a William in the row at the end of the alphabet. I
want to sort INSIDE THE COUNT on Name Desc, but when I use Order By Name
Desc, it ignores it. Very hard!!!

Any help is greatly appreciated!

Gary.
PS - Sorry if I have no explained this properly - very hard.

Erland Sommarskog
3/18/2004 10:32:05 PM
Gary W (gary@garywhittle.co.uk) writes:
[quoted text, click to view]

I have some difficulties to understand you are trying to do. For starters,
the query you posted, is illegal SQL, so what your actual query is, I don't
know.

So this is a bit too much of a guessing game for me to be willing to
take the task. A general advice for questions of this kind is that
you include:

o CREATE TABLE statements for your table.
o INSERT statements with sample data.
o The desired output from that sample data.

--
Erland Sommarskog, SQL Server MVP, sommar@algonet.se

Books Online for SQL Server SP3 at
ryanofford NO[at]SPAM hotmail.com
3/19/2004 8:13:01 AM
Not very clear what you want (as noted by Erland), and I would expect
that the SQL provided would fail. Perhaps you need to look at the
grouping you are doing. If you post something more detailed (and
clear) in terms of what you want, I'm sure someone will answer it for
you.

As a wild guess, are you looking for something like ? :

Select Count(*), PID, ID, Name
From Table 1
Group By PID, ID, Name

This would give you a count by each of the three other fields you
mention.

R

[quoted text, click to view]
louisducnguyen NO[at]SPAM hotmail.com
3/19/2004 1:18:03 PM
[quoted text, click to view]

A shot in the dark. "Distinct" sorts the resultset by all the cols
and eliminate dupes (using all cols as keys). Actually, I'm puzzled
the sql runs at all because ID & Name are not in the Group by or
wrapped with an aggregate function.

Select PID, ID, Name, count(*)
From Table 1
Group By PID, ID, Name

OR

Select PID, max(ID) as ID, max(Name) as Name, count(*)
From Table 1
Group By PID

AddThis Social Bookmark Button