如何从列中提取数据并插入数组并添加值
How to extract data from column and insert into an array and add the values
数据库:
ID | CID | HOURS
1 | 201 | 8, 8, 8, 8
2 | 201 | 2, 4, 7, 5
3 | 201 | 4, 3, 7, 1
如何提取 HOURS 列中的值并添加这些值以在 HTML table:
上生成结果
TOTAL HOURS: 14 | 15 | 22 | 14
我假设 Hours 列中的值需要插入到数组中?所以,我做了一个 while 循环并分解结果并得到以下内容:
while($row = sqlsrv_fetch_object($result)) {
$hours = explode(', ', $hours)
}
我执行 print_r($hours, 1) 并得到以下结果:
Array
(
[0] => 8
[1] => 8
[2] => 8
[3] => 8
Array
(
[0] => 2
[1] => 4
[2] => 7
[3] => 5
)
Array
(
[0] => 4
[1] => 3
[2] => 7
[3] => 1
)
如何循环执行计算?
抛开逗号分隔的数据是一种反模式,它 可能 到 return 您在单个查询中的聚合值,而无需循环遍历任何内容使用 string_split
,其基础是:
select
Sum(case col when 1 then v end),
Sum(case col when 2 then v end),
Sum(case col when 3 then v end),
Sum(case col when 4 then v end)
from (
select v, row_number() over(partition by id order by id) col
from t
cross apply(
select Cast(value as int)v from String_Split(t.hours,',')
)v
)v
数据库:
ID | CID | HOURS
1 | 201 | 8, 8, 8, 8
2 | 201 | 2, 4, 7, 5
3 | 201 | 4, 3, 7, 1
如何提取 HOURS 列中的值并添加这些值以在 HTML table:
上生成结果 TOTAL HOURS: 14 | 15 | 22 | 14
我假设 Hours 列中的值需要插入到数组中?所以,我做了一个 while 循环并分解结果并得到以下内容:
while($row = sqlsrv_fetch_object($result)) {
$hours = explode(', ', $hours)
}
我执行 print_r($hours, 1) 并得到以下结果:
Array
(
[0] => 8
[1] => 8
[2] => 8
[3] => 8
Array
(
[0] => 2
[1] => 4
[2] => 7
[3] => 5
)
Array
(
[0] => 4
[1] => 3
[2] => 7
[3] => 1
)
如何循环执行计算?
抛开逗号分隔的数据是一种反模式,它 可能 到 return 您在单个查询中的聚合值,而无需循环遍历任何内容使用 string_split
,其基础是:
select
Sum(case col when 1 then v end),
Sum(case col when 2 then v end),
Sum(case col when 3 then v end),
Sum(case col when 4 then v end)
from (
select v, row_number() over(partition by id order by id) col
from t
cross apply(
select Cast(value as int)v from String_Split(t.hours,',')
)v
)v