多源旋转单源数据

时间:2010-05-19 01:46:10

标签: sql sql-server-2008 pivot

我正在尝试mutlipivot源数据(如下所示)

alt text http://img532.imageshack.us/img532/5418/sourcex.jpg

希望结果为单行(如下所示)

alt text http://img35.imageshack.us/img35/1517/expected.jpg

到目前为止,我的查询是

SELECT  *
FROM    ( SELECT    *
      FROM      ( SELECT    NK,
                            DC,
                            VERSION,
                            GEV
                  FROM      MULTIPIVOT
                ) SRC PIVOT ( MAX(GEV) FOR DC IN ( [10], [11], [12], [18] ) ) AS PVT
    ) SRC PIVOT ( MAX([18]) FOR VERSION IN ( [2006], [2007], [2008],[2009] ) )AS PVT

输出结果

alt text http://img22.imageshack.us/img22/8703/resultos.jpg

将此作为单行的方法是什么?

由于

1 个答案:

答案 0 :(得分:0)

我认为数据库设计存在一个缺陷,如果你有两个非常不同类型的值(一年和版本号)存储在同一列中,并且某些东西应该和不应该出现在给定的逻辑中column有点朦胧,但是,有一种方法可以在一行中得到你想要的结果,假设奇数存储是一致的。

Select NK
    , Min( Case When DC = 10 Then GEV End ) As [10]
    , Min( Case When DC = 11 Then GEV End ) As [11]
    , Min( Case When DC = 12 Then GEV End ) As [12]
    , Min( Case When DC = 18 And Version = 2006 Then GEV End ) As [2006]
    , Min( Case When DC = 18 And Version = 2007 Then GEV End ) As [2007]
    , Min( Case When DC = 18 And Version = 2008 Then GEV End ) As [2008]
    , Min( Case When DC = 18 And Version = 2009 Then GEV End ) As [2009]
From Multipivot
Group By NK