0

我有一张桌子,除了最近的日期外,我想在其中提取所有日期。我尝试了以下方法,但它给了我一个错误“聚合可能不会出现在 WHERE 子句中,除非它位于 HAVING 子句或选择列表中包含的子查询中”

这是我尝试过的:

SELECT 
groupId, 
Types,
MAX(Dates) as date

FROM TableData

Where Dates < Max(dates)

GROUP BY 
groupId, 
Types

//The table looks as follows:
ID      |   GroupID | Date
1       |     A     | 10-10-2020 -> don't show
2       |     A     | 09-10-2020
3       |     A     | 08-10-2020
4       |     B     | 10-10-2020 -> don't show
5       |     B     | 09-10-2020
6       |     B     | 08-10-2020


//Expected result:
GroupID | Date
  A     | 09-10-2020
  A     | 08-10-2020
  B     | 09-10-2020
  B     | 08-10-2020
4

2 回答 2

1

DENSE_RANK你也可以使用

select max_cte as (
    select *, dense_rank() over (parition by id order by [dates] desc) max_rnk
    from TableData)
select Id, [Types], MAX(Dates) as [date]
from max_cte 
where max_rnk>1
group by Id, [Types];
于 2020-10-10T13:09:22.917 回答
0

如果您希望表中的所有行都希望其日期与表中的最新日期匹配,则一个选项使用子查询:

select t.*
from tabledata t
where date < (select max(date) from tabledata)

您也可以使用窗口函数来表达这一点(但不一定会表现得更好):

select *
from (select t.*, max(date) over() max_date from tabledata t) t
where date < max_date

编辑:如果您希望基于每个逻辑id,那么我们需要关联子查询:

select t.*
from tabledata t
where date < (select max(t1.date) from tabledata t1 where t1.id = t.id)

partition by...或在窗口中使用子句max()

select *
from (select t.*, max(date) over(partition by id) max_date from tabledata t) t
where date < max_date
于 2020-10-10T12:13:08.620 回答