这样的聚合查询如何写?
表如下
Aid Aname Bid Bname Cid Cname
a01 axp b01 bxp c01 cxp
a01 axp b01 bxp c02 cts
a01 axp b01 bxp c03 cgg
a02 agt b05 bmg c06 ckk
a02 agt b05 bmg c07 cgk
a02 agt b06 b4m c11 cgx
如何生成以下情况:
A B C
a01$axp b01$bxp c01$cxp|c02$cts|c03$cgg
a02$agt b05$bmg|b06$b4m c11$cgx
------解决方案----------------------可以得到這樣的結果
--建立測試環境
Create Table TEST
(Aid Varchar(10),
Aname Varchar(10),
Bid Varchar(10),
Bname Varchar(10),
Cid Varchar(10),
Cname Varchar(10))
--插入數據
Insert TEST Select 'a01 ', 'axp ', 'b01 ', 'bxp ', 'c01 ', 'cxp '
Union All Select 'a01 ', 'axp ', 'b01 ', 'bxp ', 'c02 ', 'cts '
Union All Select 'a01 ', 'axp ', 'b01 ', 'bxp ', 'c03 ', 'cgg '
Union All Select 'a02 ', 'agt ', 'b05 ', 'bmg ', 'c06 ', 'ckk '
Union All Select 'a02 ', 'agt ', 'b05 ', 'bmg ', 'c07 ', 'cgk '
Union All Select 'a02 ', 'agt ', 'b06 ', 'b4m ', 'c11 ', 'cgx '
GO
--建立函數
Create Function F_TEST(@Aid Varchar(10), @Aname Varchar(10), @Flag Bit)
Returns Varchar(8000)
As
Begin
Declare @S Varchar(8000)
Select @S = ' '
If @Flag = 0
Select @S = @S + '| ' + IsNull(Bid, ' ') + '$ ' + IsNull(Bname, ' ') From TEST Where Aid = @Aid And Aname = @Aname Group By Bid, Bname
Else
Select @S = @S + '| ' + IsNull(Cid, ' ') + '$ ' + IsNull(Cname, ' ') From TEST Where Aid = @Aid And Aname = @Aname Group By Cid, Cname
Select @S = Stuff(@S, 1, 1, ' ')
Return @S
End
GO
--測試
Select
Aid + '$ ' + Aname As A,
dbo.F_TEST(Aid, Aname, 0) As B,
dbo.F_TEST(Aid, Aname, 1) As C
From
TEST
Group By
Aid, Aname
GO
--刪除測試環境
Drop Table TEST
Drop Function F_TEST
--結果
/*
A B C
a01$axp b01$bxp c01$cxp|c02$cts|c03$cgg
a02$agt b05$bmg|b06$b4m c06$ckk|c07$cgk|c11$cgx
*/