你如何连续几年在sql中总结

时间:2015-10-20 17:57:59

标签: mysql

我正在使用拉赫曼棒球数据库http://seanlahman.com/files/database/readme2012.txt,并尝试查询数据库,列出总薪水为1.5倍的每支球队连续两年的总薪水,球队名称和年份和前一年一样多。

很难想出一个查询来总结每年和每支球队所有球员的薪水,并连续两年这样做。从现在开始不确定是否会产生任何影响,但我添加了我想要实现的目标。

这是我现在的查询

Select S1.yearID, S1.teamID, S2.yearID, S2.teamID, sum(S1.salary),sum(S2.salary)
from salaries as S1 , salaries as S2
where S1.yearID +1 = S2.yearID and S1.teamID = S2.teamID
group by S1.teamID

这是工资表

CREATE TABLE "salaries" (
"yearID" int NOT NULL DEFAULT '0',
"teamID" varchar(3) NOT NULL DEFAULT '',
"lgID" varchar(2) NOT NULL DEFAULT '',
"masterID" varchar(9) NOT NULL DEFAULT '',
"salary" float DEFAULT NULL,
PRIMARY KEY ("yearID","teamID","lgID","masterID")
);

这是我尝试实现enter image description here

的查询结果

2 个答案:

答案 0 :(得分:1)

几乎就在那里,只需将它们放在第一行的列中就像这样。

Select S1.yearID, S1.teamID, S2.yearID, S2.teamID, sum(S1.salary+S2.salary)
from salaries as S1 , salaries as S2
where S1.yearID +1 = S2.yearID and S1.teamID = S2.teamID
group by S1.teamID, S1.yearID

我认为应该给出你想要的东西,试一试。

修改:考虑您的评论和更新:

Select *, `Previous Salary`/`Salary` * 100 AS `Percent Increase` from (
Select S1.teamID AS `Team Name`, 
       S1.lgID AS `League`, 
       S1.yearID AS `Previous Year`, 
       sum(S1.salary) AS `Previous Salary`,
       S2.yearID AS `Year`,  
       sum(S2.salary) AS `Salary`
from salaries as S1 , salaries as S2
where S1.yearID -1 = S2.yearID and S1.teamID = S2.teamID
group by S1.teamID) salaries

答案 1 :(得分:0)

你可以这样做:

create table salaries (yearid int, teamid int, salary int);
insert into salaries values 
(2010, 1, 1), (2012, 1, 2), (2013, 1, 3), (2014, 1, 4),
(2010, 2, 1), (2011, 2, 1), (2013, 2, 3), (2014, 2, 4);

select concat(coalesce(a.yearid,'na'), ' to ', coalesce(b.yearid,'na')) as yr, a.teamid, sum(coalesce(a.salary,0) + coalesce(b.salary,0)) as salary2yr
from salaries a
left join salaries b on 
    a.teamid = b.teamid and 
    a.yearid = b.yearid-1
group by a.teamid, concat(coalesce(a.yearid,'na'), ' to ', coalesce(b.yearid,'na'))
order by a.teamid, yr

结果

yr           | teamid | salary2yr
2010 to na   | 1      | 1
2012 to 2013 | 1      | 5
2013 to 2014 | 1      | 7
2014 to na   | 1      | 4
2010 to 2011 | 2      | 2
2011 to na   | 2      | 1
2013 to 2014 | 2      | 7
2014 to na   | 2      | 4