2014-09-23 90 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