【发布时间】:2018-07-05 08:46:57
【问题描述】:
我正在学习 sql(我正在使用 postgresql),我想问一下是否有人可以帮助我进行查询。
我正在尝试从销售表中获取一些数据,并将其与客户帐户表和分支表中的数据进行匹配。
以下是我的查询,它工作正常。但是我注意到一些销售值是相乘的,因为在帐户名称(客户帐户)所在的表中,一个帐户有 2 行数据。 在客户帐户表中是带有修改日期的列。所以,我确定我只能选择最近的行。但我不知道如何将它添加到我的查询中。请问有人可以帮忙吗?
select s.accountid,
ca.accountname,
s.branchnumber,
b.branchname,
sum(s.revenue) as revenue,
sum(s.revenue)-sum(s.cost) as gp
from sales s
left join customeraccount ca on s.accountid = ca.accountid and s.company = ca.company
left join branches b on s.branchnumber = b.branchnumber and s.company = b.company
where s.company = 'FR1'
and s.salestype = 1
and s.deliverydate between '2018-01-01' and '2018-06-30'
group by s.accountid, ca.accountname, s.branchnumber, b.branchname
`
【问题讨论】:
-
所以客户帐户有两行具有相同的 accountid 和 accountname 和 company 但不同的修改日期?
-
帐户和国家始终相同。如果帐户被重命名,帐户名称可能会不同。因此,最近修改日期的行具有正确的数据。
标签: sql postgresql aggregate-functions