【问题标题】:In SQL, I need to the max of a column and return the max and the corresponding date在 SQL 中,我需要一列的最大值并返回最大值和相应的日期
【发布时间】:2021-04-17 00:04:40
【问题描述】:

我一直在研究这个问题并发现了几个类似的问题,但所提供的答案都不适用于我的情况。所以,我想伸出手直接提出我的立场

基本上,我需要返回一个最大值,其中月份等于一月、二月或三月(第一季度)等等,每个名称的第二季度到第四季度,并返回最大值发生的对应日期.

例如,我的表格可能看起来像这样:(但是,还有更多的名称和日期和货币值)

Name Money Date
John 1000 1-15-20
John 200 5-30-20
John 2000 8-30-20
John 800 11-19-20

我需要这样的表格返回:

Name Q1 Max Date Q2 Max Date Q3 Max Date Q4 Max Date
John 1000 1-15-20 200 5-30-20 2000 8-30-20 800 11-19-20

【问题讨论】:

  • 你写的查询和得到的当前输出是什么?
  • 用您正在使用的数据库标记您的问题。

标签: sql


【解决方案1】:

您要查找的查询应如下所示:

with data as (
  select 'John' as name, 1000 as "money", cast('1-15-20' as date) as "date" union all
  select 'John', 200, cast('5-30-20' as date) union all
  select 'John', 2000, cast('8-30-20' as date) union all
  select 'John', 800, cast('11-19-20' as date)
)
select
  name,
  max(case when month("date") in (1,2,3) then money else null end) as Q1Max,
  max(case when month("date") in (1,2,3) then date else null end) as "DateQ1",
  max(case when month("date") in (4,5,6) then money else null end) as Q2Max,
  max(case when month("date") in (4,5,6) then date else null end) as "DateQ2",
  max(case when month("date") in (7,8,9) then money else null end) as Q3Max,
  max(case when month("date") in (7,8,9) then date else null end) as "DateQ3",
  max(case when month("date") in (10,11,12) then money else null end) as Q4Max,
  max(case when month("date") in (10,11,12) then date else null end) as "DateQ4"
from data
group by name

当月份在case when中的条件组中时,您只需要获取最大值

输出

name Q1Max DateQ1 Q2Max DateQ2 Q3Max DateQ3 Q4Max DateQ4
John 1000 2020-01-15 200 2020-05-30 2000 2020-08-30 800 2020-11-19

【讨论】:

  • 使用sql server,你没有提供你正在使用的数据库引擎
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-10-08
  • 1970-01-01
  • 1970-01-01
  • 2021-02-28
  • 2015-09-12
  • 1970-01-01
  • 2022-01-03
相关资源
最近更新 更多