将多行重组为一行

时间:2013-08-28 09:42:12

标签: mysql sql linq sql-server-2008-r2

假设我使用查询

这个表

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'列不会给出我想要的结果。

还有其他建议吗?

提前致谢

1 个答案:

答案 0 :(得分:2)

您需要向其添加SUMMINMAX,如下所示:

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中的查询将未聚合的项目留在组中,即使您知道每个项目最多只有一个非空条目。