2014-09-23 92 views
0

我正在尝试将一系列行转换为一行,以便数据可以显示在报表上。将多个SQL行/列合并为一个单行

我的数据,我的表CustomData被提出,像这样:

CustomDataID(PK) CustomDataDefinition ReferenceTablePKValue IntValue DateTimeValue StringValue 
1      Number     1638    1230   NULL   NULL 
2      1stDate     1638    NULL  2014-09-23  NULL 
3      2ndDate     1638    NULL  2014-09-25  NULL 
4      3rdDate     1638    NULL  2014-09-25  NULL 
5      Notes     1638    NULL   NULL   Test note. 

我的目标是有这样的事情。基本上我需要它把它作为一行。

Number 1stDate  2ndDate  3rdDate  Notes 
1230 2014-09-23 2014-09-25 2014-09-25 Test note. 

我曾尝试过各种SELECT报表有多个JOINs,但是这并没有被证明卓有成效的。我在想可能会有一张临时表,但我真的不太熟悉这种方式的效果。有没有人对我如何能够适当地转换这些数据有任何想法?如果您需要更多信息,请告诉我。

+3

搜索“转动”或“交叉表”。这已经在全国各地被回答了数十亿次。 – 2014-09-23 20:05:01

回答

0

取决于你试图做多少行,简单的方法来返回你正在寻找的将是使用case语句,如果你想为一堆不同的变量做这个,然后做一个bunnch cse语句不是很有趣,在那一点上,我会考虑旋转你的数据。

select 
case when CustomDataDefinition = 'Number' then intvalue end 'Number', 
case when CustomDataDefinition = '1stDate' then datetimevalue end '1stDate', 
case when CustomDataDefinition = '2ndDate' then datetimevalue end '2ndDate', 
case when CustomDataDefinition = '3rdDate' then datetimevalue end '3rdDate', 
case when CustomDataDefinition = 'Notes' then stringvalue end 'Notes' 



from 
*yourtable* 
1

因为有你不能在这里使用支点不同类型的,所以你可以使用那是旋转功能之前的功能:

with t(CustomDataID, CustomDataDefinition, ReferenceTablePKValue 
     , IntValue, DateTimeValue, StringValue) as (
    select 1, 'Number', 1638, 1230, NULL, NULL union all 
    select 2, '1stDate', 1638, NULL, '2014-09-23', NULL union all 
    select 3, '2ndDate', 1638, NULL, '2014-09-25', NULL union all 
    select 4, '3rdDate', 1638, NULL, '2014-09-25', NULL union all 
    select 5, 'Notes', 1638, NULL, NULL, 'Test note' 
) 
select ReferenceTablePKValue 
    , max(case 
      when CustomDataDefinition = 'Number' then intvalue 
      end) "number" 
    , max(case 
      when CustomDataDefinition = '1stDate' then datetimevalue 
      end) "1stDate" 
    , max(case 
      when CustomDataDefinition = '2ndDate' then datetimevalue 
      end) "2ndDate" 
    , max(case 
      when CustomDataDefinition = '3rdDate' then datetimevalue 
      end) "3rdDate" 
    , max(case 
      when CustomDataDefinition = 'Notes' then stringvalue 
      end) "Notes" 
    from t 
group by ReferenceTablePKValue 

REFERENCETABLEPKVALUE NUMBER 1STDATE  2NDDATE  3RDDATE NOTES 
----------------------------------------------------------------------------- 
       1638  1230 2014-09-23 2014-09-25 2014-09-25 Test note 

SQLFiddle