创建 3 个新列,基于交易时期(年、月、最大年)。

huangapple go评论55阅读模式
英文:

Create 3 new columns based off of transaction period (year, month, max year)

问题

Column [TRAN_YRNO] 包含年月数据,格式为YYYYMM(例如 202304)。我正在尝试将其拆分为两列,一列是月份,一列是年份。然后我想创建一个包含最大年份的第三列(对于所有行都应为2023)。

SELECT 
   [TNET]
  ,[SORTCODE]    
  ,[LOADDATE]
  ,[TRAN_YRMO]
FROM [dbo].[tbl_941_Monthly_Cumulative]
SELECT c.*, c.[year]
from  c
LEFT JOIN b
ON c.[year] = b.[Max Year]

(SELECT
*,
LEFT([TRAN_YRMO],4) as 'Year' ,
RIGHT([TRAN_YRMO],2) as 'Month'
FROM [dbo].[tbl_941_Monthly_Cumulative])c

(SELECT
MAX(a.[year]) AS 'Max Year'

from 

(SELECT *,
LEFT([TRAN_YRMO],4) as 'Year' ,
RIGHT([TRAN_YRMO],2) as 'Month'
FROM [dbo].[tbl_941_Monthly_Cumulative])a)b

这是我迄今为止尝试过的内容,显然出现了错误。

目标是获得类似以下的结果:

TNET SORTCODE LOADDATE TRAN_YRMO YEAR MONTH MAX YEAR
202304 2023 04 2023
202301 2023 01 2023
202208 2022 08 2023
202107 2021 07 2023
英文:

Column [TRAN_YRNO] contains month/year data in the format YYYYMM (ex. 202304). I am trying to split this into two columns, one for month and one for year. I then want to create a third column that contains the max year. (should be 2023 for all rows)

SELECT 
       [TNET]
      ,[SORTCODE]    
      ,[LOADDATE]
      ,[TRAN_YRMO]
  FROM [dbo].[tbl_941_Monthly_Cumulative]
SELECT c.*, c.[year]
from  c
LEFT JOIN b
ON c.[year] = b.[Max Year]

(SELECT
*,
LEFT([TRAN_YRMO],4) as 'Year' ,
RIGHT([TRAN_YRMO],2) as 'Month'
FROM [dbo].[tbl_941_Monthly_Cumulative])c

(SELECT
MAX(a.[year]) AS 'Max Year'

from 

(SELECT *,
LEFT([TRAN_YRMO],4) as 'Year' ,
RIGHT([TRAN_YRMO],2) as 'Month'
FROM [dbo].[tbl_941_Monthly_Cumulative])a)b

Here is what I have tried so far, which obviously errors out.

The goal is to have something that looks like:

TNET SORTCODE LOADDATE TRAN_YRMO YEAR MONTH MAX YEAR
202304 2023 04 2023
202301 2023 01 2023
202208 2022 08 2023
202107 2021 07 2023

答案1

得分: 1

只是另一种使用窗口函数 max() over()Cross Apply 计算表达式的方法。

可选:将 left/right 包装在 convert(int,...) 中。

选择 A.*
,B.Year
,B.Month
,MaxYear = max(B.Year) over()
从 YourTable A
Cross Apply ( values ( left([TRAN_YRMO],4),right([TRAN_YRMO],2) ) )B(Year,Month)

英文:

Just another approach using the window function max() over() and a Cross Apply to calculate the expressions once

Optional: wrap the left/right in a convert(int,...)

Select A.*
      ,B.Year
	  ,B.Month
	  ,MaxYear = max(B.Year) over()
 From  YourTable A
 Cross Apply ( values ( left([TRAN_YRMO],4),right([TRAN_YRMO],2) ) )B(Year,Month)

huangapple
  • 本文由 发表于 2023年4月7日 01:01:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/75952023.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定