如何将行转换为DataGridView中的列

时间:2013-06-15 13:39:34

标签: sql vb.net winforms datagridview pivot

我有

的数据网格视图
   CATEGORY         PROJECT    AMOUNT 
   ========         =======    ======
   Miscellaneous    project1     1200
   Miscellaneous    project2     4500
   Travel           project3     3000
   Miscellaneous    project4     2300
   Travel           project4     1000

我想将上述格式转换为

       CATEGORY       project1   project2   project3    project4
       ========       ========   ========   ========    ========
       Miscellaneous   1200       4500         0         2300
       Travel           0           0         3000       1000

project_name是动态的,可以更改

请帮助.....

2 个答案:

答案 0 :(得分:1)

由于您使用的是SQL Server,因此可以使用PIVOT函数将数据行转换为列。

如果您有一定数量的值,那么您可以对查询进行硬编码:

select category,
  coalesce(project1, 0) project1,
  coalesce(project2, 0) project2,
  coalesce(project3, 0) project3,
  coalesce(project4, 0) project4
from 
(
  select category, project, amount
  from yt
) d
pivot
(
  sum(amount)
  for project in (project1, project2, project3, project4)
) piv;

请参阅SQL Fiddle with Demo

但是在你的情况下,听起来你会有一个未知数量的值,因此你必须实现一个动态的SQL解决方案:

DECLARE @cols AS NVARCHAR(MAX),
    @colsNull AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(PROJECT) 
                    from yt
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

select @colsNull = STUFF((SELECT distinct ', Coalesce(' + QUOTENAME(PROJECT) +', 0) as '+ QUOTENAME(PROJECT)
                    from yt
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT category,' + @colsNull + ' 
            from 
            (
                select category, project, amount
                from yt
            ) d
            pivot 
            (
                sum(amount)
                for project in (' + @cols + ')
            ) p '

execute(@query);

SQL Fiddle with Demo。两者都会给出结果:

|      CATEGORY | PROJECT1 | PROJECT2 | PROJECT3 | PROJECT4 |
-------------------------------------------------------------
| Miscellaneous |     1200 |     4500 |        0 |     2300 |
|        Travel |        0 |        0 |     3000 |     1000 |

答案 1 :(得分:0)

使用数据透视查询从sql获取数据..并根据需要从sql获取结果