以前的回答有很多爭議。我會盡力根據您所展示的內容提供最簡單的解決方案。如果您有多年的時間,或者您在任何一個月都有空數據,您將需要爲自己解決一些問題。在嘗試引導你去理解而不真正做所有的工作時,事實上我已經給你一個確切的解決方案。您需要調整並退回其中的某些內容,以處理數據中的漏洞或其他可能的邊緣情況。總而言之,它應該引導您採取一種方法,您可以利用這種方法來處理這些其他可能性。它確實使用查詢查詢來挑出標題行。我認爲這是導致更復雜解決方案的部分。
<cfscript>
GetTotalStars = querynew(
"dept_id,csedept_name,totalstars,year,month",
"integer, varChar, integer, integer, integer",
[
{
dept_id:1
,csedept_name:'department 1'
,totalstars:5
,year:2014
,month:5
}
,{
dept_id:1
,csedept_name:'department 1'
,totalstars:4
,year:2014
,month:6
}
,{
dept_id:2
,csedept_name:'department 2'
,totalstars:3
,year:2014
,month:5
}
,{
dept_id:2
,csedept_name:'department 2'
,totalstars:6
,year:2014
,month:6
}
]
);
writedump(GetTotalStars);
</cfscript>
<!---
I agree with previous arguments about exessive use of query of queries.
But for your header row (and to get a full list of possible months), you
really need to pull that out of the original query in a single list or array or struct
--->
<cfquery dbtype="query" name="qryMonths">
select distinct [month] from GetTotalStars order by [month]
</cfquery>
<cfoutput>
<table border="1">
<thead>
<tr>
<th>Department</th>
<!---
If you have gaps in the data, it might make sense to build an
array here to keep track of what month is in what column
--->
<cfloop query="qryMonths">
<th>#MonthAsString(qryMonths.month)#</th>
</cfloop>
</tr>
</thead>
<tbody>
<!---
This is just a straightforward nested query and group loop.
If you have nulls in the data, you would check against the array
that you built in the top section to figure out which column you
are in
--->
<cfloop query="GetTotalStars" group="csedept_name">
<tr>
<td>#GetTotalStars.csedept_name#</td>
<cfloop group="month">
<td>#GetTotalStars.totalstars#</td>
</cfloop>
</tr>
</cfloop>
</tbody>
</table>
</cfoutput>
作爲@邁克爾建議,優選如果可能的話,以在數據庫中聚集。 1)你的DBMS是什麼? 2)這些結果是否跨越多年(2013,2014,...)? – Leigh