如何在每个月的最后一天列出列值?

时间:2014-03-20 16:13:06

标签: sql-server-2008

表1:

Day         Campaign    Placement               Site    Impressions
3/1/2014    Boy Dog         ROS_728x90              CNN         100
3/2/2014    Boy Dog         Leaderboard             ESPN    250
3/3/2014    Boy Dog         RM_Something_300x250        CNN         38
3/2/2014    Boy Dog         ROS_728x90              CNN         102

表1是每日数据。表2是每月表。

表2:

Month   Year    Campaign    Placement        Site    Actual Cost
3           2014    Boy Dog         ROS_728x90       CNN            1000
3           2014    Boy Dog         Leaderboard      ESPN           850
3           2014    Boy Dog         RM_Something_300x250 CNN            421

从表1和表2中,我想制作如下所示的Final Table。此外,从表2中我只想包括每月基数的费用,并希望在每个月的最后一天设置所有展示位置,如下表所示。

有成千上万的Placement,我想为所有地方做同样的事情,就像我在决赛桌中提到的只有一个位置。我正在使用SQL Server 2008 R2。

决赛桌:

Day Campaign    Placement   Impressions Cost
3/1/2014    Boy Dog ROS_728x90  100          0
3/2/2014    Boy Dog ROS_728x90  102          0
3/3/2014    Boy Dog ROS_728x90  102          0
3/4/2014    Boy Dog ROS_728x90  102          0
3/31/2014   Boy Dog ROS_728x90  500          0
3/31/2014   Boy Dog ROS_728x90  0            1000

1 个答案:

答案 0 :(得分:0)

如果你想要一个选择

select *, cost from 
table1 t1
left join table2 t2 
on year(t1.Day) = t2.year
 and month(t1.Day) = t2.month

仅针对最后一天的选择费用(如果我理解的话)使用此选择

select *,
     case
         when  DATEADD(d, -1, DATEADD(m, DATEDIFF(m, 0, t1.day) + 1, 0)) = t1.day then cost
         else 0
     end
from table1 t1
left join table2 t2 
on year(t1.Day) = t2.year
and month(t1.Day) = t2.month