2017-01-03 86 views
-2

我试图编写逻辑以获得低于输出但未成功。我的头脑 现在空白。你能和我分享你的想法吗?我确定我们一起 可以找出一些SQL中最简单的解决方案,以获得以下 输出。交叉加入以获得特定月份在特定年份的所有季度末月份

添加更多,我不想Q4键。 请注意,表格是包含更多列的月份维度,例如 Prev01,02 ...个月份的键。

标签为SQL Server & Teradata以及我关心的逻辑只有&不是语法。我正在使用Teradata。

现有数据:

enter image description here

预期输出:

enter image description here

一年总那么预期的记录将是12 * 3 = 36

编辑:对于每一年,我们估计&预算值。例如。

2016年,估算值将来自2016年3月(Q1),2016年6月(Q2),2016年9月(Q3)。还有一个预算值将从2015年12月(Q4)开始。 因此,2016年的任何一个月都会有相同的预算估算值。这只会在年份发生变化时才会改变。我希望现在很清楚......

不幸的是,我不能共享表DDL或示例数据。所以试图尽可能简单地解释场景。我能够编写SQL来获得预算值,但对于估计,情况有点棘手。因此,让我们说2016年4月,我想要的估算值是2016年3月,2016年6月,2016年9月。 现有数据是一个类似于样本数据的截图。

添加更多,月份密钥就像一个标识列。一月至2017年将有一个月键13 &等等...

+1

看起来,'Quarter_End'包含来自JAN **的月数**。 – Vikrant

+2

请分享相关表格DDL语句和样本数据作为DML。你在这里已经有一段时间了,现在你应该知道分享代码和图像更好。 –

+0

目前还不清楚你实际需要什么。我们不知道为什么你会在一月,三月,六月和九月。为什么不与8月例如?这里有适用的规则吗?然后有列quarter_start和quarter_end,其价值似乎没有多大意义。在表中,它似乎只是一个月每年季度的数字。在结果中,它似乎是连接月份的月份数或month_key。我不知道哪个。 –

回答

1

select t1.month_key, t1.Month, Year, t3.Month+'-'+right(CAST(Year as varchar(4)),2) Scenario, t2.month_key Quarter_End 
from YourData t1 
cross join (
    select Quarter_Start, MAX(month_key) month_key 
    from YourData 
    group by Quarter_Start 
) t2 
join (
    select month_key, Month 
    from YourData 
) t3 on t2.month_key = t3.month_key 
where t2.month_key<>12 -- if you do not want last quarter 
order by 1,5 
+0

谢谢。帮助我建立自己的东西! – Aditya

+0

欢迎您,很高兴知道 – MtwStark

1

在MSSQL中,我们可以做如下:

declare @temp table (month_key int,Months varchar(100),Years int,Quarter_Start int) 
insert into @temp values (1 ,'Jan',2016, 1 ) 
insert into @temp values (2 ,'Feb',2016, 1 ) 
insert into @temp values (3 ,'Mar',2016, 1 ) 
insert into @temp values (4 ,'Apr',2016, 2 ) 
insert into @temp values (5 ,'May',2016, 2 ) 
insert into @temp values (6 ,'Jun',2016, 2 ) 
insert into @temp values (7 ,'Jul',2016, 3 ) 
insert into @temp values (8 ,'Aug',2016, 3) 
insert into @temp values (9 ,'Sep',2016, 3) 
insert into @temp values (10,'Oct',2016, 4) 
insert into @temp values (11,'Nov',2016, 4) 
insert into @temp values (12,'Dec',2016, 4) 

select 1 as 'Month_Key','Jan' as 'Month',Years,Months+'-16' as 'Scenario',month_key as 'Quarter End' from @temp where month_key in 
(select max(month_key) from @temp group by Quarter_Start) 
+0

谢谢你的回答。但是,这对于提供的样本数据非常具体。我需要一个通用的解决方案:) – Aditya

相关问题