简体   繁体   中英

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.

For example, my table maybe looks like this: (However, there are many more names and date and money values)

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

And i would need a table return like this:

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

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

OUTPUT

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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