如何在sql中合并计数值
Posted
技术标签:
【中文标题】如何在sql中合并计数值【英文标题】:how to merge count values in sql 【发布时间】:2015-01-29 20:22:54 【问题描述】:我正在尝试将桌队的所有城市值更新为:“城市”+“#p”+“玩家数量”+“g”+“前进目标数量”(例如“Tokyo #p25 g74” )。
我尝试这样做并有这两个查询。一种用于获取球员数量,一种用于获取进球数。
查询玩家人数:
select t.city + '#p' + CONVERT(varchar(10), count(pt.playerId)) + '#g'
from team t,
player_team pt
where pt.teamID = t.teamID
group By t.teamId,t.city
查询进球数:
select count(*) totalgoals,
pt.teamID
from goals g,
player_team pt
where g.playerId = pt.playerId
group by pt.teamID
我无法合并这两个计数。 请帮帮我...
还有我的表格层次结构和字段,如下所示
player
(
playerID int,
firstName nvarchar(25),
lastName nvarchar(25),
nationality varchar(25),
birthDate smalldatetime,
age smallint,
position varchar(25)
)
team
(
teamID int,
name nvarchar(50),
city nvarchar(25)
)
player_team
(
playerID int,
teamID int,
season varchar(5)
)
match
(
matchID int,
homeTeamID int,
visitingTeamID int,
dateOfMatch smalldatetime,
week tinyint
)
goals
(
matchID int,
playerID int,
isOwnGoal bit,
minute tinyint
)
编辑:使用下面给出的选择查询效果很好,并给了我正确的结果。但是我怎样才能用这多条记录更新表?当我尝试将其作为子查询更新到更新语句时,它给了我编译错误并抱怨多记录...
错误:子查询返回超过 1 个值。当子查询跟随 =、!=、、>= 或子查询用作表达式时,这是不允许的。
【问题讨论】:
mysql、sql-server 和 splite?这么多标签.. 那么当你更新了城市之后,当你进球更多时你会怎么做? SQL Server 使用+
进行连接,所以我认为这就是 OP 正在使用的...
【参考方案1】:
假设您的 2 个查询产生了所需的结果,请尝试将它们与 outer join
和子查询结合起来:
select pt.teamId,
t.city + ' #p' + CONVERT(varchar(10), count(pt.playerId))
+ ' g' + CONVERT(varchar(10), t2.totalgoals)
from team t
inner join player_team pt on pt.teamID = t.teamID
left join (
select count(*) totalgoals,
pt.teamID
from goals g inner join player_team pt on g.playerId = pt.playerId
group by pt.teamID
) t2 on t.teamid = t2.teamid
group By pt.teamId,t.city,t2.totalgoals
SQL Fiddle Demo
【讨论】:
嗯,谢谢。它对我很有效。select 语句让我获得了多个值。那么我怎样才能用这些多条记录更新表呢?当我尝试将其更新为子查询时,它会给我编译错误并抱怨多记录 @Webster -- 您可以使用带有连接的更新:sqlfiddle.com/#!3/bdb5b/1。但是,您确定要更新城市字段还是只想要包含该数据的新视图...【参考方案2】:最简单的方法可能是使用相关子查询来查找每个团队的值:
SELECT t.city || ' #p' ||
CONVERT(varchar(10), (SELECT count(*)
FROM player_team
WHERE teamId = t.teamId))
|| ' #g ' ||
CONVERT(varchar(10), (SELECT count(*)
FROM goals
JOIN player_team USING (playerId)
WHERE teamId = t.teamId))
FROM team t
【讨论】:
【参考方案3】:试试这个:
SELECT a.city '#p' + CONVERT(varchar(10), a.playerCount) + '#g' + CONVERT(varchar(10), b.totalgoals)
FROM (SELECT t.teamId, t.city, count(pt.playerId) as playerCount
FROM team t JOIN player_team pt on (t.teamID = pt.teamID)
GROUP BY t.teamId, t.city)a JOIN
(SELECT pt.teamId, count(*) as totalgoals,
FROM goals g JOIN player_team pt on (g.playerId = pt.playerId)
GROUP BY pt.teamId) b ON (a.teamId = b.teamId)
【讨论】:
以上是关于如何在sql中合并计数值的主要内容,如果未能解决你的问题,请参考以下文章