我想在同一行中返回特定度量在不同時間範圍內的結果。 例如「過去30天」,「過去7天」,「過去3天」。 爲此,我最初使用了UNION
函數,併爲每個時間範圍創建了多個子查詢。這樣做的缺點是我收集了相同的數字三次,隨之而來的運行時間增加。包含日期邊界以分段選擇結果
一位同事建議我使用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。我該怎麼做才能解決這個問題?