SQL concat case select 尝试添加上个月数据的新列时
SQL concat case select when trying to add new column of previous month data
我有一个数据集,我需要在其中连接上个月的月份和年份。问题是它跨越了两年多。我需要创建一个语句,其中表示月 - 1 = 0,月变为 12 和年 - 1。
Select concat(case
when month > 1 then select(month-1, year)
when month = 1 then select(12, year -1)
else select(month-1, year)
end
作为月年
来自 table
如果您将 month
和 year
作为单独的列并且想要减去一个月,那么您可以使用:
select (case when month > 1 then year else year - 1 end) as year,
(case when month > 1 then month - 1 else 12 end) as month
您需要 concat() 中的 2 个 CASE 语句,用于月份和年份:
select
concat(
case when month > 1 then month - 1 else 12 end,
case when month > 1 then year else year - 1 end
)
这是一个不同的方法(尝试使用 SQLite3,根据您的 SQL 语法进行相应调整):
-- some test data first
create table t(yy,mm);
insert into t values
(2018,1),(2018,2),(2018,3),(2018,4),(2018,5),(2018,6),
(2018,7),(2018,8),(2018,9),(2018,10),(2018,11),(2018,12),
(2019,1),(2019,2),(2019,3),(2019,4),(2019,5),(2019,6),
(2019,7),(2019,8),(2019,9),(2019,10),(2019,11),(2019,12),
(2020,1),(2020,2),(2020,3),(2020,4),(2020,5),(2020,6),
(2020,7),(2020,8),(2020,9),(2020,10),(2020,11),(2020,12);
-- current year and month, year of previous month and previous month
select yy,mm,yy-((mm+10)%12+1)/12 as yy_1,(mm+10)%12+1 mm_1 from t;
我有一个数据集,我需要在其中连接上个月的月份和年份。问题是它跨越了两年多。我需要创建一个语句,其中表示月 - 1 = 0,月变为 12 和年 - 1。
Select concat(case
when month > 1 then select(month-1, year)
when month = 1 then select(12, year -1)
else select(month-1, year)
end
作为月年 来自 table
如果您将 month
和 year
作为单独的列并且想要减去一个月,那么您可以使用:
select (case when month > 1 then year else year - 1 end) as year,
(case when month > 1 then month - 1 else 12 end) as month
您需要 concat() 中的 2 个 CASE 语句,用于月份和年份:
select
concat(
case when month > 1 then month - 1 else 12 end,
case when month > 1 then year else year - 1 end
)
这是一个不同的方法(尝试使用 SQLite3,根据您的 SQL 语法进行相应调整):
-- some test data first
create table t(yy,mm);
insert into t values
(2018,1),(2018,2),(2018,3),(2018,4),(2018,5),(2018,6),
(2018,7),(2018,8),(2018,9),(2018,10),(2018,11),(2018,12),
(2019,1),(2019,2),(2019,3),(2019,4),(2019,5),(2019,6),
(2019,7),(2019,8),(2019,9),(2019,10),(2019,11),(2019,12),
(2020,1),(2020,2),(2020,3),(2020,4),(2020,5),(2020,6),
(2020,7),(2020,8),(2020,9),(2020,10),(2020,11),(2020,12);
-- current year and month, year of previous month and previous month
select yy,mm,yy-((mm+10)%12+1)/12 as yy_1,(mm+10)%12+1 mm_1 from t;