0
**CODE**    **TYPE**
 --------------------
  XXOPT      POD
  XXOPT      FPOD
  MSC        OPR
  KLM        OPR
  40DV       SZTP
  90DV       SZTP
  MMVD       POD
  KKLP       FPOD
  SSRG       FPOD

我有一个来自数据库的数据表

我想按照以下格式显示我的结果

注意:这里的 POD、FPOD、OPR、SZTP 是静态类型

POD:  XXOPT,MMVD 
FPOD: XXOPT,KKLP,SSRG
OPR:  MSC,KLM  
SZTP: 40DV, 90DV

  WILL YOU PLESSE HELP ME TO SHOW ABOVE FORMAT AS OUT PUT.
4

1 回答 1

0
DECLARE @MyTable TABLE(
    [CODE]  NVARCHAR(50) NOT NULL,
    [TYPE]  NVARCHAR(50) NOT NULL
);
INSERT  @MyTable ([CODE],[TYPE])
SELECT 'XXOPT','POD'
UNION ALL SELECT 'XXOPT','FPOD'
UNION ALL SELECT 'MSC','OPR'
UNION ALL SELECT 'KLM','OPR'
UNION ALL SELECT '40DV','SZTP'
UNION ALL SELECT '90DV','SZTP'
UNION ALL SELECT 'MMVD','POD'
UNION ALL SELECT 'KKLP','FPOD'
UNION ALL SELECT 'SSRG','FPOD';

SELECT  x.[TYPE],y.GROUP_CONCAT
FROM    (SELECT [TYPE] FROM @MyTable GROUP BY [TYPE]) x
CROSS APPLY(
    SELECT STUFF((SELECT    ','+y.CODE
    FROM    @MyTable y
    WHERE   y.[TYPE]=x.[TYPE]
    FOR XML PATH('')),1,1,'') AS GROUP_CONCAT
)y;

结果:

TYPE GROUP_CONCAT
---- ---------------
FPOD XXOPT,KKLP,SSRG
OPR  MSC,KLM
POD  XXOPT,MMVD
SZTP 40DV,90DV

注意:在这种情况下,您需要 ([TYPE])+INCLUDE([CODE]) 上的索引或 ([TYPE],[CODE]) 上的索引。

于 2013-07-23T17:16:57.067 回答