英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论