SQL Select 除最近日期外的所有内容
SQL Select everything besides the most recent date
我有一个 table,我想在其中提取除最近日期之外的所有日期。我尝试了以下但它给了我一个错误“聚合可能不会出现在 WHERE 子句中,除非它位于包含在 HAVING 子句或 select 列表中的子查询中”
这是我试过的:
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
如果您希望 table 中的所有行都希望日期与 table 中的最新日期相匹配的行,一个选项使用子查询:
select t.*
from tabledata t
where date < (select max(date) from tabledata)
你也可以用window函数来表达(但不一定表现得更好):
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)
... 或在 window max()
:
中使用 partition by
子句
select *
from (select t.*, max(date) over(partition by id) max_date from tabledata t) t
where date < max_date
你也可以使用 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];
我有一个 table,我想在其中提取除最近日期之外的所有日期。我尝试了以下但它给了我一个错误“聚合可能不会出现在 WHERE 子句中,除非它位于包含在 HAVING 子句或 select 列表中的子查询中”
这是我试过的:
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
如果您希望 table 中的所有行都希望日期与 table 中的最新日期相匹配的行,一个选项使用子查询:
select t.*
from tabledata t
where date < (select max(date) from tabledata)
你也可以用window函数来表达(但不一定表现得更好):
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)
... 或在 window max()
:
partition by
子句
select *
from (select t.*, max(date) over(partition by id) max_date from tabledata t) t
where date < max_date
你也可以使用 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];