mysql - 将多行重新组合为一行

标签 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 子句中。

将“Wins”和“Competition”列放入 GROUP BY 子句中不会给出我想要的结果。

还有其他建议吗?

提前致谢

最佳答案

您需要向其中添加 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 中的查询将未聚合的项目保留在组中。

关于mysql - 将多行重新组合为一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18484422/

相关文章:

php - 使用 PHP 检查是否可以在短时间内从本地应用程序访问 MySql 在线服务器

c# - DataAdapter.Update() 如何与存储过程一起使用

mysql - #1241 - 操作数应包含 1 列 IN

sql - Django ORM中多对多字段的复杂计数

sql - 使用 SQL 选择连续年份数据

mysql - 有人可以帮我用 R 编程解决这个问题吗?

c# - 如果值大于零,LINQ 包括 "&&"运算符

java - 尝试运行在线项目时出现 CannotGetJDBCConnectionException

c# - 为什么 LINQ Where 搜索查询在 List<> 上比 ConcurrentBag<> 更快

c# - Linq最小日期最大日期模型查询