我正在使用MSSQL,我有一个看起来像这样的表:
table1
id | name | description | apply start | apply end
1 | 100-A | desc1 | start1 | end1
2 | 100-B | desc1 | start1 | end1
3 | 100-C | desc1 | start1 | end1
4 | 200-H | desc2 | start2 | end2
5 | 300-B | desc3 | start3 | end3
6 | 300-C | desc3 | start3 | end3
我正在尝试使用php将数据库中的这些值输出到表中,所以看起来像这样:
Name | Description | Starting From | End
----------------------------------------------------
|100-A | | | |
|100-B | desc1 | start1 | end1 |
|100-C | | | |
|--------------------------------------------------
|200-H | desc2 | start2 | end2 |
|--------------------------------------------------
|300-B | | | |
|300-C | desc3 | start3 | end3 |
|--------------------------------------------------
如果所有值都相同,那么有没有办法对description,apply_start和apply_end列进行分组?
答案 0 :(得分:1)
以下是我将如何在PHP中执行此操作的基本思路(假设您的描述中不会显示空字符,apply_start和apply_end列)。
// Assuming a result in this format
$result = array(
array("id" => "1",
"name" => "100-A",
"description" => "desc1",
"apply_start" => "start1",
"apply_end" => "end1"),
. . .
);
foreach ($result as $row) {
$groups[$row['description'] . "\0"
. $row['apply_start'] . "\0"
. $row['apply_end']][] = $row['name'];
}
foreach ($groups as $desc => $names) {
echo implode(',', $names) . ' | ';
echo implode(' | ', explode("\0", $desc)) . "\n";
}
输出:
100-A,100-B,100-C | desc1 | start1 | end1
200-H | desc2 | start2 | end2
300-B,300-C | desc3 | start3 | end3
答案 1 :(得分:0)
在行格式化方面,并非如此,这是PHP的工作。但是,您可以通过向结果集添加内容来简化您的生活:
SELECT [name], [description], [apply start], [apply end]
, COUNT([NAME])OVER(PARITION BY [description], [apply start], [apply end]) AS RowSpan
FROM table1
ORDER BY [description], [apply start], [apply end], [name]
现在,在使用PHP构建表时,请使用RowSpan作为分组列。您甚至可以在for循环中使用它,根据图表将Name输出到表格的单个单元格中。
答案 2 :(得分:0)
正如Jaaz Cole所说,你应该用PHP做这件事,我不确定我是否通过提供这个帮助你,但如果你真的坚持的话,可以在SQL中完成。
SELECT DISTINCT
STUFF(((
SELECT ' ' + [Name]
FROM table1 t
WHERE t.[description] = table1.[description]
AND t.[apply start] = table1.[apply start]
AND t.[apply end] = table1.[apply end]
FOR XML PATH (''), ROOT('x'), TYPE).value('/x[1]', 'VARCHAR(MAX)')
), 1, 1, '') AS [Name],
[description] AS [Description],
[apply start] AS [Starting From],
[apply end] AS [End]
FROM table1