[英]In SQL, I need to the max of a column and return the max and the corresponding date
我一直在研究這個問題並發現了幾個類似的問題,但所提供的答案都不適用於我的情況。 所以,我想伸出手直接擺出我的姿勢
基本上,我需要返回一個最大值,其中月份等於 1 月、2 月或 3 月(第一季度)等等,每個名稱的第二季度到第四季度,並返回最大值發生的對應日期。
例如,我的表可能看起來像這樣:(但是,還有更多的名稱、日期和貨幣值)
姓名 | 錢 | 日期 |
---|---|---|
約翰 | 1000 | 1-15-20 |
約翰 | 200 | 5-30-20 |
約翰 | 2000 | 8-30-20 |
約翰 | 800 | 11-19-20 |
我需要一個這樣的表返回:
姓名 | Q1 最大值 | 日期 | Q2 最大值 | 日期 | Q3 最大值 | 日期 | 第四季度最大 | 日期 |
---|---|---|---|---|---|---|---|---|
約翰 | 1000 | 1-15-20 | 200 | 5-30-20 | 2000 | 8-30-20 | 800 | 11-19-20 |
您要查找的查詢應如下所示:
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
獲得最大值
OUTPUT
姓名 | Q1Max | 日期Q1 | Q2Max | 日期Q2 | Q3Max | 日期Q3 | Q4Max | 日期Q4 |
---|---|---|---|---|---|---|---|---|
約翰 | 1000 | 2020-01-15 | 200 | 2020-05-30 | 2000 | 2020-08-30 | 800 | 2020-11-19 |
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.