我有这张桌子,向我展示了卖家的每周销售情况。我当前的查询(附件)只有两列。我想添加第三列,其中包含年初至今的销售数据。有人可以就此提供帮助,我可以添加到当前的SQL语句中吗?
select t2.Source, coalesce(t1."This Week",0) "This Week"
from sellers t2 left outer join
(select Source,min("Week") as Week, sum(Sales) "This Week"
from salesdata
where Week = date_trunc('week', now())::date - 1
group by Source, Week) t1
on t1.Source = t2.Source
当前结果:
Source This Week
Judith 18
Thedia 64
Alfonso 0
Michael 15
Jordan 0
期望的结果:
Source This Week YTD
Judith 18 100
Thedia 64 150
Alfonso 0 258
Michael 15 487
Jordan 0 78
答案 0 :(得分:1)
假设您的表格中的字段week
类型为date
:
SELECT source, week, "This Week", "YTD"
FROM (
SELECT source, week, coalesce(sum(sales), 0) AS "This Week"
FROM salesdata
WHERE week = date_trunc('week', now()) - 1) sw
JOIN (
SELECT source, coalesce(sum(sales), 0) AS "YTD"
FROM salesdata
WHERE date_trunc('year', week) = date_trunc('year', now()) sy USING (source);
请注意,您不需要sellers
表,所有信息都可以来自salesdata
表。