简体   繁体   English

在 SQL 中,我需要一列的最大值并返回最大值和相应的日期

[英]In SQL, I need to the max of a column and return the max and the corresponding date

I have been researching this problem and have found a couple of similar questions, but none of the answers provided have worked for my situation.我一直在研究这个问题并发现了几个类似的问题,但所提供的答案都不适用于我的情况。 So, I wanted to reach out and directly pose my aituation所以,我想伸出手直接摆出我的姿势

Basically, I need to return a max value where months are equal to January, February, or march (first quarter) and so on with the second quarter through the fourth quarter for each name and return the correspinding date that max value occurred.基本上,我需要返回一个最大值,其中月份等于 1 月、2 月或 3 月(第一季度)等等,每个名称的第二季度到第四季度,并返回最大值发生的对应日期。

For example, my table maybe looks like this: (However, there are many more names and date and money values)例如,我的表可能看起来像这样:(但是,还有更多的名称、日期和货币值)

Name姓名 Money Date日期
John约翰 1000 1000 1-15-20 1-15-20
John约翰 200 200 5-30-20 5-30-20
John约翰 2000 2000 8-30-20 8-30-20
John约翰 800 800 11-19-20 11-19-20

And i would need a table return like this:我需要一个这样的表返回:

Name姓名 Q1 Max Q1 最大值 Date日期 Q2 Max Q2 最大值 Date日期 Q3 Max Q3 最大值 Date日期 Q4 Max第四季度最大 Date日期
John约翰 1000 1000 1-15-20 1-15-20 200 200 5-30-20 5-30-20 2000 2000 8-30-20 8-30-20 800 800 11-19-20 11-19-20

The query you are looking for should look like this:您要查找的查询应如下所示:

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

You just need to get the max when the months are in the group of the condition in the case when您只需要在月份处于条件组的case when获得最大值

OUTPUT OUTPUT

name姓名 Q1Max Q1Max DateQ1日期Q1 Q2Max Q2Max DateQ2日期Q2 Q3Max Q3Max DateQ3日期Q3 Q4Max Q4Max DateQ4日期Q4
John约翰 1000 1000 2020-01-15 2020-01-15 200 200 2020-05-30 2020-05-30 2000 2000 2020-08-30 2020-08-30 800 800 2020-11-19 2020-11-19

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM