我需要编写一个SQL查询,它会从表中获取具有文件最大值的那些行。
数据库表如下:
> 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
现在从这个表中我想得到那些按ID分组的最大文件的行:
> ID status dept files
>
> 1 1 39 1256642968
>
> 2 1 93 1256810937
>
> 3 0 20 1256642968
>
> 5 1 342 1256810937
有什么建议吗?
感谢。
我试过这个,但这不对
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
答案 0 :(得分:4)
用你的表替换@ t1:
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
答案 1 :(得分:2)
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
答案 2 :(得分:0)
SELECT MAX(files) as max_files, id, status, dept
FROM table
GROUP BY id
答案 3 :(得分:0)
我可能过度简化了问题,但是:
select top 5 * from SLAStat order by files desc;