前两列效果很好,但我不知道如何获得第三列的结果。请告诉我如何让第三列按照本周显示年初至今的数据。请提供帮助。
select "Builder","Traffic", sum(cast("Traffic" as int)) as YTD
from trafficdatapcr
where "Week" = '2016-12-11'
group by "Builder","Traffic"
样本数据:
Week Builder Traffic
2016-12-11 Macys 100
2016-10-11 Bloomingdales 15
2016-08-11 Saks 85
2016-02-11 Cole Haan 95
2015-12-25 Kroger 65
我目前的成绩:
Builder Traffic YTD
Macys 100 100
预期结果:
Builder Traffic YTD
Macys 100 100
Saks 0 85
Bloomingdales 0 15
Cole Haan 0 95
Kroger 0 65
答案 0 :(得分:1)
您的where子句正在删除您想要的记录,使用案例有条件地显示所需周的流量而不是where子句
select "Builder"
, case when "Week" = to_date('2016-12-11',YYYY-MM-DD') then "Traffic" else 0 end as "Traffic"
, sum(cast("Traffic" as int)) as YTD
from trafficdatapcr
group by "Builder","Traffic"
Order by week Desc
虽然如果有人选择2016-10-11,那么YTD将是所有日期......看起来确实有点奇怪......所以也许你想要有条件地求和......
select "Builder"
, case when "Week" = to_date('2016-12-11','YYYY-MM-DD') then "Traffic" else 0 end as "Traffic"
, sum(case when "week"<=to_date('2016-12-11','YYYY-MM-DD') then cast("Traffic" as int) else 0 end) as YTD
from trafficdatapcr
group by "Builder","Traffic"
Order by week Desc
这样
所以第二个查询应该返回(2016-10-11的日期),但是日期顺序正确(不知道你想要的订单)
Builder Traffic YTD
Macys 0 0
Saks 0 85
Bloomingdales 15 15
Cole Haan 0 95
Kroger 0 65