2011-06-23 98 views
1

不幸的是,我無法完全理解前面的例子。另一個關鍵的SQL Server查詢

我想創建一個基於多年來對棒球MVP進行投票的表格,並將其與現在可用的更爲客觀的測量WAR相比較。我希望根據這個價值觀看兩位頂級球員之間的差異。這裏是代碼只顯示一個許多

select season,division,player,rankMVP as MVP,WAR,rankWAR 
from mlbmvpvoting 
where (season = '1955' or season = '1956') 
and rankWAR < 3 
order by season,division,rankWAR 

season division player     MVP WAR rankWAR 
1955 AL Mickey Mantle     5 9.5  1 
1955 AL Al Kaline      2 9.0  2 
1955 NL Willie Mays      4 9.3  1 
1955 NL Duke Snider      2 8.9  2 
1956 AL Mickey Mantle     1 12.9 1 
1956 AL Early Wynn      13 8.5  2 
1956 NL Duke Snider      10 7.7  1 
1956 NL Hank Aaron      3 7.5  2 

幾年我想產生這樣的

season division pl_1   pl_2  MVP_1 MVP_2 WAR_1 WAR_2 
1955  AL Mickey Mantle Al Kaline 5  2  9.5  9.0 
1955  N Willy Mays  Duke Snider 4  2  9.3  8.9 

TIA

回答

1

使用分組和有條件的聚集,像這樣:

SELECT 
    season, 
    division, 
    pl_1 = MAX(CASE rankWAR WHEN 1 THEN player END), 
    pl_2 = MAX(CASE rankWAR WHEN 2 THEN player END), 
    MVP_1 = MAX(CASE rankWAR WHEN 1 THEN rankMVP END), 
    MVP_2 = MAX(CASE rankWAR WHEN 2 THEN rankMVP END), 
    WAR_1 = MAX(CASE rankWAR WHEN 1 THEN WAR  END), 
    WAR_2 = MAX(CASE rankWAR WHEN 2 THEN WAR  END) 
FROM mlbmvpvoting 
WHERE season IN ('1955', '1956') 
    AND rankWAR IN (1, 2) 
GROUP BY season, division 
ORDER BY season, division 

INOR<基本都optimisable,因此我適時改變的條件。

+0

謝謝你。我只是延長到所有季節與任何季節IN(選擇不同季節 從mlbmvpvoting ),並走了。如果有人對使用結果進行分析感興趣 - 特別是與Willie Mays有關 - 我在http://tinyurl.com/6kr28dl – pssguy

0

看看這樣的解決方案適合你:

with mlbmvpvoting (season, division, player, MVP, WAR, rankWAR) as 
(
    select 1955, 'AL', 'Mickey Mantle', 5, 9.5,  1 union all 
    select 1955, 'AL', 'Al Kaline',  2, 9.0,  2 union all 
    select 1955, 'NL', 'Willie Mays', 4, 9.3,  1 union all 
    select 1955, 'NL', 'Duke Snider', 2, 8.9,  2 union all 
    select 1956, 'AL', 'Mickey Mantle', 1, 12.9, 1 union all 
    select 1956, 'AL', 'Early Wynn',  13, 8.5,  2 union all 
    select 1956, 'NL', 'Duke Snider', 10, 7.7,  1 union all 
    select 1956, 'NL', 'Hank Aaron',  3, 7.5,  2 
) 
select 
    season, 
    division, 
    pl_1 = max(case rankWAR when 1 then player end), 
    pl_2 = max(case rankWAR when 2 then player end), 
    MVP_1 = max(case rankWAR when 1 then MVP end), 
    MVP_2 = max(case rankWAR when 2 then MVP end), 
    WAR_1 = max(case rankWAR when 1 then WAR end), 
    WAR_2 = max(case rankWAR when 2 then WAR end) 
from mlbmvpvoting 
group by season, division 
order by season; 
+0

感謝您的輸入 – pssguy