SQL Server查询包含group by和having的所有列

SQL Server查询包含group by和having的所有列,sql,sql-server,database,sybase,Sql,Sql Server,Database,Sybase,我想知道是否有一种方法可以在SQL Server中使用group by和HAVE查询所有列?例如,我有6列,a,b,…,f,这是我想要得到的: Select * From table Group by table.b, table.c Having max(table.d)=table.d 这在sybase中有效,因为我正在尝试将东西从sybase迁移到SQL Server,所以我不确定在新环境中可以做什么。谢谢。在select中不使用任何加积门函数时,为什么要按每列分组?只需使用以下代码获取

我想知道是否有一种方法可以在SQL Server中使用group by和HAVE查询所有列?例如,我有6列,a,b,…,f,这是我想要得到的:

Select *
From table
Group by table.b, table.c
Having max(table.d)=table.d

这在sybase中有效,因为我正在尝试将东西从sybase迁移到SQL Server,所以我不确定在新环境中可以做什么。谢谢。

在select中不使用任何加积门函数时,为什么要按每列分组?只需使用以下代码获取表的所有列:

select * from table
Group by仅在select中具有加积函数(例如max()、avg()、count()、…)时使用


对加总列和表中正常列进行了限制。

您可以使用OVER子句中的
MIN、MAX、AVG和COUNT函数为每列提供聚合值(模拟每列的group by子句)和公共表表达式CTE来过滤结果(模仿having条款)为:


如果您希望为
b
c
的每个组合获取最大
d
的行,则使用
不存在

select t.* from tablename t
where not exists (
  select 1 from tablename
  where b = t.b and c = t.c and d > t.d 
) 
或使用
rank()
窗口功能:

select t.a, t.b, t.c, t.d, t.e, t.f
from (
  select *, 
    rank() over (partition by b, c order by d desc) rn
  from tablename
) t
where t.rn = 1

无需使用have即可获得所需的结果。请尝试以下操作

Select table.b, table.c, max(table.d)
From table
Group by table.b, table.c

当您需要所有列时,需要在SQL Server中使用窗口函数,例如
行数
。您好,因为我需要筛选出每个组的最大d,假设有一些记录具有相同的b,c,并且我希望获得具有最大d的记录,这就是为什么我需要group和having子句的原因。
Select table.b, table.c, max(table.d)
From table
Group by table.b, table.c