最近做統計功能的時候常常需要用到合併分組內容,如果只根據分組統計數值用聚合函數就可以了,如果處理分組後的字串列呢,我們就必須要自己寫函數處理了,例如有這樣的資料資訊:
要將上面資料分組,取得統計結果:
實現方式一:# :利用T- SQL 技術產生
XML
的方法
-- ================================================ -- Description:合并分组内容 -- Author:夏保华 -- Date:2009-08-06 -- ================================================ create table Employees(DepartmentName varchar(50),EmpoyeeName varchar(20)) insert into Employees select '开发部','小刘' union all select '开发部','小王' union all select '开发部','小张' union all select '工程部','老吴' union all select '工程部','老李' union all select '市场部','大兵' union all select '市场部','大黄' union all select '市场部','大虾' union all select '市场部','大国' go create function Sum_ByGroup(@DepartmentName varchar(50)) returns varchar(8000) as begin declare @ret varchar(8000) set @ret = '' select @ret = @ret+','+EmpoyeeName from Employees where DepartmentName = @DepartmentName set @ret = stuff(@ret,1,1,'') return @ret end go select DepartmentName,dbo.Sum_ByGroup(DepartmentName) as EmployeesList from Employees group by DepartmentName go
#擴充:For XML Path
1.在該 XML 中,所產生的行集中的每個欄位值都包在元素中。由於 SELECT 子句未指定任何列名別名,因此產生的子元素名稱與 SELECT 子句中對應的列名相同。如果未對path指定任何訊息,針對行集中的每一行,將會新增一個 <row
> 標記。
SQL語句:<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:xml;toolbar:false">select
DepartmentName,
stuff
((
select
&#39;
,
&#39;
+
EmpoyeeName
from
Employees
where
DepartmentName
=
e.DepartmentName
for
xml path(
&#39;&#39;
)),
1
,
1
,
&#39;&#39;
)
as
EmployeesList
from
Employees E
group
by
DepartmentName</pre><div class="contentsignin">登入後複製</div></div>
如:
行元素名稱,以覆蓋預設的<
row
>。例如,以下
將針對行集中的每一行傳回對應的 <
Employee
> 元素。
SQL語句:<div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:sql;toolbar:false">select
DepartmentName,(
select
&#39;&#39;
+
EmpoyeeName
from
Employees
where
DepartmentName
=
e.DepartmentName
for
xml path)
as
EmployeesList
from
Employees E
group
by
DepartmentName</pre><div class="contentsignin">登入後複製</div></div>
3.如果指定零長度字串,則不會產生包裝元素。
結果:
語句:
select DepartmentName,( select '' + EmpoyeeName from Employees where DepartmentName = e.DepartmentName for xml path( ' Employee ' )) as EmployeesList from Employees E group by DepartmentName
以上是利用XML FOR PATH合併分組資訊的範例程式碼(圖文)的詳細內容。更多資訊請關注PHP中文網其他相關文章!