如何在没有SQL过程的情况下转置列

时间:2016-06-23 15:18:20

标签: c# sql sql-server datagridview pivot

我有一个SQL表,可以保存如下图所示的值

Original table

现在我需要转换这个表,如下所示。

Transposed table

我需要在不使用存储过程的情况下执行此操作。我正在尝试将第二个表绑定到4个datagridview复选框列。

1 个答案:

答案 0 :(得分:1)

如果您的C2中的值并非总是[MP], [KL], [OL], [IFL],那么您可能需要尝试使其动态化。如果您的数据集相对较大,请小心使用CROSS JOIN:< / p>

示例数据:

IF OBJECT_ID('tempdb..#temp') IS NOT NULL
    DROP TABLE #temp;

CREATE TABLE #temp(C1 INT
              , C2 VARCHAR(10));

INSERT INTO #temp
VALUES
      (1
     , 'MP'),
      (2
     , 'KL'),
      (3
     , 'OL'),
      (3
     , 'IFL');

QUERY:

SELECT DISTINCT
      C1
    , [MP] = CASE
               WHEN [MP] = C1 THEN 'TRUE'
               ELSE ''
            END
    , [KL] = CASE
               WHEN [KL] = C1 THEN 'TRUE'
               ELSE ''
            END
    , [OL] = CASE
               WHEN [OL] = C1 THEN 'TRUE'
               ELSE ''
            END
    , [IFL] = CASE
                WHEN [IFL] = C1 THEN 'TRUE'
                ELSE ''
            END
FROM   #temp AS A
      CROSS JOIN
              (SELECT [MP]
                   , [KL]
                   , [OL]
                   , [IFL]
               FROM
                    (SELECT C1
                         , C2
                     FROM   #temp) AS SourceTable PIVOT(MAX(C1) FOR C2 IN([MP]
                                                              , [KL]
                                                              , [OL]
                                                              , [IFL])) AS PivotTable) AS B;

结果:

enter image description here