我正在学习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
`
答案 0 :(得分:0)
这是我的解决方法:
此查询将为您提供accountid
+ accountname
+ company
的唯一组合,这是每个accountid
+ company
的最后修改的行>
SELECT customeraccount.accountid, customeraccount.accountname, customeraccount.company
FROM customeraccount
INNER JOIN
(SELECT accountid, company, max(modified_on) AS last_modified_on
FROM customeraccount
group by accountid, company) AS customeraccount_last_modified
ON customeraccount.accountid = customeraccount_last_modified.accountid
AND customeraccount.company = customeraccount_last_modified.company
AND customeraccount.modified_on = customeraccount_last_modified.last_modified_on
展开:
我们希望为每个modified_on
+ accountid
建立一个最后修改日期(我称为company
):
SELECT accountid, company, max(modified_on) AS last_modified_on
FROM customeraccount
group by accountid, company
现在,我们要从具有accountname
值的行中提取modified_on
,作为我们之前提取的最后一个修改。因此,根据查询中三列的相等性,在customeraccount
和pt.1中的查询(仅用作此查询的临时表)之间创建了连接。然后您可以从customeraccount
中获取任何所需的列,并确保您对每个accountid
+ company
获得唯一值(希望很清楚...)
您可以接受此查询并将其放在查询中的FROM
子句中,请确保为其创建别名。
答案 1 :(得分:0)
with lastdate as (
Select accountid,
company,
max(modified_date) modified_date
from customeraccount
group by accountid,
company )
,cutomers as (
Select accountid,
company,
accountname
from customeraccount
inner join lastdate on (lastdate.accountid = customeraccount.accountid and
lastdate.company = customeraccount.company and
lastdate.modified_date = customeraccount.modified_date ))
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 cutomers 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
-HTH