如何从SQL中的字符串列聚合数字
我正在处理一个设计糟糕的数据库列,它的值如下如何从SQL中的字符串列聚合数字,sql,sql-server,group-by,aggregate,Sql,Sql Server,Group By,Aggregate,我正在处理一个设计糟糕的数据库列,它的值如下 ID cid Score 1 1 3 out of 3 2 1 1 out of 5 3 2 3 out of 6 4 3 7 out of 10 cid sum percentage 1 4 out of 8 50 2 3 out of 6 50 3 7 out of 10 70 我希望在cid上
ID cid Score
1 1 3 out of 3
2 1 1 out of 5
3 2 3 out of 6
4 3 7 out of 10
cid sum percentage
1 4 out of 8 50
2 3 out of 6 50
3 7 out of 10 70
我希望在cid上对合计总和和分数百分比列进行分组,如下所示
ID cid Score
1 1 3 out of 3
2 1 1 out of 5
3 2 3 out of 6
4 3 7 out of 10
cid sum percentage
1 4 out of 8 50
2 3 out of 6 50
3 7 out of 10 70
我该怎么做 您可以这样尝试:
select
t.cid
, cast(sum(s.a) as varchar(5)) +
' out of ' +
cast(sum(s.b) as varchar(5)) as sum
, ((cast(sum(s.a) as decimal))/sum(s.b))*100 as percentage
from MyTable t
inner join
(select
id
, cast(substring(score,0,2) as Int) a
, cast(substring(score,charindex('out of', score)+7,len(score)) as int) b
from MyTable
) s on s.id = t.id
group by t.cid
[]重新设计表格,但作为CTE随时可用。这里有一个解决方案,它并没有尽可能短,但它利用了方便的SQL Server函数PARSENAME。如果希望截断而不是四舍五入,或者希望百分比为十进制值而不是整数,则可能需要调整百分比计算 在这个或大多数解决方案中,您必须依靠列值来确定您所显示的特定格式的分数。如果你有一点点疑问,你应该进行一些其他检查,这样你就不会遗漏或误解任何东西
with
P(ID, cid, Score2Parse) as (
select
ID,
cid,
replace(Score,space(1),'.')
from scores
),
S(ID,cid,pts,tot) as (
select
ID,
cid,
cast(parsename(Score2Parse,4) as int),
cast(parsename(Score2Parse,1) as int)
from P
)
select
cid, cast(round(100e0*sum(pts)/sum(tot),0) as int) as percentage
from S
group by cid;
重新设计表格。把专栏一分为二有多难?完全同意,但在我这么做之前我需要一个快速解决方案,有什么想法吗?