1
我试图在两个表之间进行连接。完成后的查询如下:为什么我的SQL查询将结果加倍
select
cast(M.Rank as signed) as Rank,
O.Country,
O.Continent,
M.Gold,
M.Silver,
M.Bronze,
M.Total
from
(
select @rownum := @rownum + 1 as RankStd,
CASE
WHEN (@Gold=T.Gold and @Silver=T.Silver and @Bronze=T.Bronze)
THEN @rank := @rank
ELSE @rank := @rownum
END as Rank,
(@Gold:=T.Gold) Gold,
(@Silver:=T.Silver) Silver,
(@Bronze:=T.Bronze) Bronze,
T.Total,
T.City,
T.Season
from
(
select
sum(Gold) as Gold,
sum(Silver) as Silver,
sum(Bronze) as Bronze,
sum(Total) as Total,
City,
Season
from
(
select
City,
Season,
case when Medal ='gold' then 1 else 0 end as Gold,
case when Medal ='silver' then 1 else 0 end as Silver,
case when Medal ='bronze' then 1 else 0 end as Bronze,
1 as Total
from MedalResults
where Country = 'ITA'
and Season='Summer'
) a
group by City
) T
CROSS JOIN (SELECT @rownum := 0,
@Gold := 0,
@Silver := 0,
@Bronze := 0,
@rank := 1) v
order by Gold desc, Silver DESC, Bronze DESC
)M
join OrgCountry O
on O.City = M.City and O.Season=M.Season
order by Rank
在M表让我一个表,这个结构(我只写第一行):
RankStd Rank Gold Silver Bronze Total City Season
-----------------------------------------------------------
1 1 26 18 24 68 Los Angeles Summer
2 2 19 23 21 63 London Summer
3 3 17 17 14 48 Athina Summer
4 4 14 6 5 25 Antwerpen Summer
5 5 13 10 13 36 Roma Summer
6 6 13 10 12 35 Atlanta Summer
的OrgCountry表确实具有这样的结构体(I只写有意义行让你明白,明明1996年和1984年之间有其他条目,但在这个例子中我把它剪):
ID Year City Country Continent Season
-----------------------------------------------------
1 2012 London Great Britain Europe Summer
2 2008 Beijing China Asia Summer
3 2004 Athina Greece Europe Summer
4 2000 Sydney Australia Oceania Summer
5 1996 Atlanta United States Americas Summer
6 1984 Los Angeles United States Americas Summer
如果我让喜欢他们之间的连接以上,我得到的结果如下:
Rank Country Continent Gold Silver Bronze Total
-------------------------------------------------------------
1 United States Americas 26 18 24 68
1 United States Americas 26 18 24 68
2 Great Britain Europe 19 23 21 63
2 Great Britain Europe 19 23 21 63
2 Great Britain Europe 19 23 21 63
3 Greece Europe 17 17 14 48
3 Greece Europe 17 17 14 48
3 Greece Europe 17 17 14 48
为什么这样?我想要的只是汇总为国家和得到:
Rank Gold Silver Bronze Total Country Season
-----------------------------------------------------------
1 39 28 36 113 United States Summer
2 19 23 21 63 Great Britain Summer
3 17 17 14 48 Greece Summer
4 14 6 5 25 Netherlands Summer
5 13 10 13 36 Italy Summer
6 13 10 12 35 Australia Summer
等等。 请注意,由于亚特兰大和洛杉矶是美国的城市,所以第一排会更改。
见https://meta.stackoverflow.com/questions/333952/为什么我应该提供一个mcve为什么看起来对我来说是一个非常简单的sql查询 – Strawberry
我添加此页面:http://sqlfiddle.com/# !9/97ec5c/1 – Idro
那么,您是否想知道意大利在每个组织国家赢得了多少金,银和铜牌? – Strawberry