2013-08-28 35 views
2

比方說,我有這個表,我開始使用查詢重新分組的多行成一個

enter image description here

我工作的查詢,可以給像這樣

enter image description here

這是我到目前爲止所嘗試的:

Select [First Name], [Last Name], Club, 
case when Competition='La Liga' then Wins end as [La Liga], 
case when Competition='Copa del Rey' then Wins end as [Copa del Rey], 
case when Competition='Supercopa de Espana' then Wins end as [Supercopa de Espana],  
case when Competition='UEFA Champions League' then Wins end as [UEFA Champions League], 
case when Competition='UEFA Super Cup' then Wins end as [UEFA Super Cup], 
case when Competition='FIFA Club World Cup' then Wins end as [UEFA Super Cup] 

From dbo.Table 
Group by [First Name], [Last Name], Club 

但我得到'SQL執行錯誤'列'dbo.Wins'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。 列'dbo.Competition'在選擇列表中無效,因爲它不包含在聚合函數或GROUP BY子句中。

在GROUP BY子句中放置列'Wins'和'Competition'不會給出我想要的結果。

其他建議?

在此先感謝

回答

2

您需要添加SUMMIN,或MAX它,像這樣:

Select [First Name], [Last Name], Club, 
SUM(case when Competition='La Liga' then Wins end) as [La Liga], 
SUM(case when Competition='Copa del Rey' then Wins end) as [Copa del Rey], 
SUM(case when Competition='Supercopa de Espana' then Wins end) as [Supercopa de Espana],  
SUM(case when Competition='UEFA Champions League' then Wins end) as [UEFA Champions League], 
SUM(case when Competition='UEFA Super Cup' then Wins end) as [UEFA Super Cup], 
SUM(case when Competition='FIFA Club World Cup' then Wins end) as [UEFA Super Cup] 

From dbo.Table 
Group by [First Name], [Last Name], Club 

你不能在SQL Server中留下未聚集的項目組中的查詢,即使您知道每個項目最多隻有一個非空項目。

+0

謝謝你的@dasblinkenlight – Zack09