0

我有一个datagridview

   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 是动态的,可以更改

请帮助......

4

2 回答 2

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 |
于 2013-06-15T15:24:52.133 回答
0

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

于 2013-06-15T13:41:30.810 回答