[英]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.