【发布时间】:2014-03-24 11:58:53
【问题描述】:
我想在同一行中返回不同时间范围内特定度量的结果。
例如“过去 30 天”、“过去 7 天”、“过去 3 天”。
为此,我最初使用了UNION 函数,并为每个时间范围创建了多个子查询。这样做的缺点是我收集了 3 次相同的数字,因此会增加运行时间。
一位同事建议我使用CASE 函数来分割时间范围。我最初想按如下方式实现它:
select tp.Name,
case when pub.Date between DATEADD(day, -31, getdate()) and DATEADD(day, -1, getdate())
then SUM(Impressions) else 0 end 'Last 30 days Impressions',
case when pub.Date between DATEADD(day, -31, getdate()) and DATEADD(day, -1, getdate())
then SUM(Revenue * rler.Rate) else 0 end 'Last 30 days Revenues',
case when pub.Date between DATEADD(day, -8, getdate()) and DATEADD(day, -1, getdate())
then SUM(Impressions) else 0 end 'Last 7 days Impressions',
case when pub.Date between DATEADD(day, -8, getdate()) and DATEADD(day, -1, getdate())
then SUM(Revenue * rler.Rate) else 0 end 'Last 7 days Revenues',
case when pub.Date between DATEADD(day, -4, getdate()) and DATEADD(day, -1, getdate())
then SUM(Impressions) else 0 end 'Last 3 days Impressions',
case when pub.Date between DATEADD(day, -4, getdate()) and DATEADD(day, -1, getdate())
then SUM(Revenue * rler.Rate) else 0 end 'Last 3 days Revenues'
from ...
where ...
group by tp.Name, tp.Kind, pub.Date
order by 'Last 30 days Impressions'
不幸的是,这将为每个名称、种类和日期返回一行,这不是我想要的。我认为这个问题取决于GROUP BY 调用中的pub.Date。我应该怎么做才能克服这个问题?
【问题讨论】: