在子查询SQL Server中使用max(col)和count

时间:2016-03-07 22:19:25

标签: sql-server sql-server-2008

我在SQL Server中组合了一个查询但是子查询有问题 我希望使用max(loadid)并计算查询返回的记录数。

所以例如我的最后一个loadid是400,400的记录数量是2300,所以我的recor_count列应该显示2300.我已经尝试了以下各种方法,但是我遇到了错误。

select count (loadid) 
from t1 
where loadid = (select max(loadid) from t1) record_count;

(select top 1 LOADID, count(*) 
 from t1
 group by loadid
 order by count(*) desc) as Record_Count

3 个答案:

答案 0 :(得分:1)

使用分组显示loadid和匹配行数,按计数排序并使用top将输出限制为1行。

select top 1 loadid, count(*) as cnt
from t1
group by loadid
order by cnt desc

答案 1 :(得分:0)

使用内部查询中的窗口函数可能更容易实现:

SELECT COUNT(*)
FROM   (SELECT RANK() OVER (ORDER BY loadid DESC) AS rk
        FROM   t1) t
WHERE  rk = 1

答案 2 :(得分:0)

实现结果的另一种最简单的方法:

Set Nocount On;

Declare @Test Table
(
    Id      Int
)

Insert Into @Test(Id) Values
(397),(398),(399),(400)

Declare @Abc Table
(
     Id     Int
    ,Value  Varchar(100)
)

INsert Into @Abc(Id,Value) Values
 (398,'')
,(400,'')
,(397,'')
,(400,'')
,(400,'')

Select   a.Id
        ,Count(a.Value) As RecordCount
From    @Abc As a
        Join
        (
            Select  Max(t.Id) As Id
            From    @Test As t
        ) As v On a.Id = v.Id
Group By a.Id