自我加入尝试显示两年的结果

时间:2018-02-08 18:00:17

标签: mysql sql oracle

您好我有一张表,其中包括2016年和2017年的费用。

我的代码是

    select 
    sum(a.cost),a.AGENCYNAME,b.AGENCYNAME,sum(b.cost) from table as a
    where a.projectyear = 2016 and b.projectyear = 2017
    join table as b on a.USERID = b.USERID

但我无法得到答案。

3 个答案:

答案 0 :(得分:1)

也许是因为我没有清楚地理解这个问题,无法解决为什么我们需要在这里自我加入。你可以尝试一下:

select a.AGENCYNAME, a.projectyear, sum(a.cost) as TotalCost
from table a
where a.projectyear in (2016,2017)
group by a.AGENCYNAME,a.projectyear

答案 1 :(得分:1)

如果我理解你的问题,我认为你想要做的事情非常简单,可以使用CASE声明来实现。我不太确定USERID的位置。

CREATE TABLE #table(
   [userid] char(1),
   [agencyname] varchar(255),
   [projectyear] int,
   [cost] int
);
INSERT INTO #table VALUES
('A','Agency 1',2016,10),
('A','Agency 1',2016,20),
('A','Agency 1',2017,30),
('A','Agency 1',2017,40),
('A','Agency 2',2016,100),
('A','Agency 2',2016,200),
('A','Agency 2',2017,300),
('A','Agency 2',2017,400);

SELECT
       agencyname,
       SUM(CASE WHEN projectyear= 2016 THEN cost END) as 'cost 2016',
       SUM(CASE WHEN projectyear= 2017 THEN cost END) as 'cost 2017'
FROM #table
GROUP BY agencyname

DROP TABLE #table

答案 2 :(得分:0)

你加入了错误的位置,但你应该通过

添加一个合适的组
select 
sum(a.cost)
,a.AGENCYNAME
,b.AGENCYNAME
,sum(b.cost) from table as a
INNER join table as b on a.USERID = b.USERID
where a.projectyear = 2016 and b.projectyear = 2017
group by a.AGENCYNAME ,b.AGENCYNAME