views:

102

answers:

4

I need to write a SQL query which will get me those rows from the table which have the max value of files.

The database table is as follows:

> ID  status dept  files
> 
> > 1   1 23 1256637314
> > 
> > 1   1 39 1256642968
> > 
> > 2   0 85 1256551419
> > 
> > 2   1 90 1256642968
> > 
> > 2   1 93 1256810937
> > 
> > 3   0 20 1256642968
> > 
> > 5   1 342 1256810937

Now from this table i want to get those rows which have the maximum files grouping by ID:

> ID  status dept  files
>
> 1    1   39  1256642968
>
> 2    1   93  1256810937
>
> 3    0   20  1256642968
>
> 5    1   342 1256810937

Any suggestions??

Thanks.

i tried this but this is not right

Select  ID, Status, dept,files
from SLAStat
where files in (Select Max(files) from SLAStat group by ID)




2   1 90 1256642968
1   1 39 1256642968
3   0 20 1256642968
5   1 342 1256810937
2   1 93 1256810937
+2  A: 
SELECT DISTINCT a.ID, a.Status, a.Dept, a.Files
FROM table a
INNER JOIN (
SELECT ID, MAX(files) AS Files
FROM table
GROUP BY ID) b ON a.ID = b.ID AND a.Files = b.Files
Agent_9191
this doesn't guarantee 1 row per ID (if there are two ID's with the same files.. you'll get 2 rows for that ID). Look at my answer to fix this problem.
Nestor
Msg 102, Level 15, State 1, Line 3Incorrect syntax near 'InnerJoin'.Msg 102, Level 15, State 1, Line 6Incorrect syntax near 'b'.
plus this is the same thing i had done... its similar to my edited query..
i cant figure out how to get just 1 row per id.. thanks for helping tough...
Does the error message literally say 'InnerJoin' or is it 'Inner Join'? And the difference is that I'm including the ID in the subquery.
Agent_9191
@Nestor I've updated it to do a distinct lookup. All it takes is a Distinct.
Agent_9191
A: 
SELECT MAX(files) as max_files, id, status, dept
FROM table
GROUP BY id
teabot
the group by will need to have status, dept also... but if i do that all entries will be displayed... so thats not right.. thanks tough
Why will the GROUP BY need those extra columns?
teabot
A: 

I may be over-simplifying the problem, but:

select top 5 * from SLAStat order by files desc;
David Lively
this is just an example... there may be many entries in the table..
+3  A: 

Replace @t1 by your table:

With idT as (
    select ID
    from @t1
    group by id
) 
select applyT.* 
from idT p
CROSS APPLY (
    select top 1 * from @t1 where ID=p.ID order by files desc
) as applyT
Nestor
this was brilliant.... is there a place i can read about how to query like this... it will be a good learning experience for me..
SQL is a funny language. It takes practice (more than learning the syntax) to write good queries. If I could give you a pointer, I'd tell you to use "With" to separate the different steps in a query, instead of writting long queries. The query optimizer will take care of factoring out the with's for you. CROSS APPLY is an awesome feature too (it's easier to reason about it too).
Nestor