按日期分组的表格单元格中的SQL结果

时间:2013-03-14 11:42:12

标签: php sql html-table

我在SQL Server中有一个包含此字段和值的表。

ID_Employee | ID_Company | Date       | Concept | Hours
--------------------------------------------------------
      1     |      1     | 14/03/2013 |    1    |   8
      1     |      1     | 14/03/2013 |    2    |   0
      1     |      1     | 14/03/2013 |    3    |   3
      1     |      1     | 14/03/2013 |    4    |   1
      1     |      1     | 16/03/2013 |    1    |   5
      1     |      1     | 16/03/2013 |    2    |   2
      1     |      1     | 16/03/2013 |    3    |   0
      1     |      1     | 16/03/2013 |    4    |   0

我需要的是在HTML表格中显示ID_Employee=1ID_Company=1的值,按日期对行进行分组,并将其列中的小时数作为其概念值排序。< / p>

Date       | Concept_1 | Concept_2 | Concept_3 | Concept_4 |
------------------------------------------------------------
14/03/2013 |  8 hours  |  0 hours  |  3 hours  |  1 hour   |
16/03/2013 |  5 hours  |  2 hours  |  0 hours  |  0 hours  |

我不知道如何进行查询或在php中使用什么语句(while,for,foreach)为每个不同日期创建1行(<tr>),包含单个单元格({{ 1}})每个概念和小时。

html应如下所示:

<td>

这可能很容易,但现在我有点困惑,我找不到解决方案。

2 个答案:

答案 0 :(得分:1)

您正在寻找一个PIVOT运营商,可以让您做所需的事情。您可以使用以下查询:

select  
    pvt.date,
    [1] AS concept_1,
    [2] AS concept_2,
    [3] AS concept_3,
    [4] AS concept_4
from 
    (
        SELECT 
            date, 
            hours, 
            concept
        FROM table1
    ) p
PIVOT
(   
    AVG(hours)
    FOR concept IN
    ([1], [2], [3], [4]) 
) as pvt

同时提供SqlFiddle

答案 1 :(得分:0)

检查一下:

declare @tableHTML nvarchar(MAX);
set @tableHTML = CAST((

    select  
        1 AS Tag,
        NULL AS Parent,
        pvt.[date] AS 'tr!1!id',
        ltrim(rtrim(str([1])))+ ' hours' AS 'tr!1!td class="concept_1"!Element',
        ltrim(rtrim(str([2])))+ ' hours' AS 'tr!1!td class="concept_2"!Element',
        ltrim(rtrim(str([3])))+ ' hours' AS 'tr!1!td class="concept_3"!Element',
        ltrim(rtrim(str([4])))+ ' hours' AS 'tr!1!td class="concept_4"!Element'
    from 
        (
            SELECT 
                date, 
                hours, 
                concept
            FROM table1
        ) p
    PIVOT
    (   
        AVG(hours)
        FOR concept IN
        ([1], [2], [3], [4]) 
    ) as pvt
    FOR XML EXPLICIT) AS NVARCHAR(MAX));

PRINT REPLACE(REPLACE(REPLACE(REPLACE(@tableHTML, '</td class="concept_1">', '</td>'), '</td class="concept_2">', '</td>'), '</td class="concept_3">', '</td>'), '</td class="concept_4">', '</td>');

输出:

<tr id="2013-03-14">
    <td class="concept_1">8 hours</td>
    <td class="concept_2">0 hours</td>
    <td class="concept_3">3 hours</td>
    <td class="concept_4">1 hours</td>
</tr>
<tr id="2013-03-16">
    <td class="concept_1">5 hours</td>
    <td class="concept_2">2 hours</td>
    <td class="concept_3">0 hours</td>
    <td class="concept_4">0 hours</td>
</tr>

我使用 @Sergio 提出的支点 - 非常感谢(+1)