[英]SQL Results in table cells grouped by date in <TR>
我在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=1
和ID_Company=1
的值, ID_Employee=1
日期对行进行分组,并将其列中的小时数排序为其概念的值。
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>
<td>
),每个概念只包含一个单元格( <td>
)和小时。
html应该看起来像这样:
<tr id="14/03/2013">
<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 hour</td>
</tr>
<tr id="16/03/2013">
<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 hour</td>
</tr>
这可能很容易,但是现在我有些困惑,无法找到解决方案。
检查一下:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.