簡體   English   中英

php / sql:基於多個列對行進行分組

[英]php/sql: Grouping rows based on multiple columns

我正在使用MSSQL,並且有一個如下表:

表格1

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列分組?

這是我將如何在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

並非如此,當涉及行格式設置時,這就是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輸出到表的單個單元格中。

正如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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM