配对列数据安排在asp.net中

时间:2013-07-23 16:56:25

标签: asp.net sql-server-2008 sql-server-2008-r2 asp.net-4.0 asp.net-4.5

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

我有来自数据库的数据表

我希望看到我的结果如下格式

注意:HERE 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.

1 个答案:

答案 0 :(得分: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])上的索引。