2014-02-13 47 views
-1
檢索數據

我需要數據網格在我的以下形式的UIMSSQL查詢,以便從DB

 | Col1 | Col2 | Col3 | Col4 | 
-------------------------------------- 
     |  |  |  |  | 
Row1 | 10 | 20 | 30 | 40 | 
     |  |  |  |  | 
Row2 | 50 | 60 | 70 | 80 | 
     |  |  |  |  | 
Row3 | 90 | 100 | 110 | 120 | 
     |  |  |  |  | 
Row4 | 130 | 140 | 150 | 160 | 

上述數據網格的模式被存儲在DB作爲

表T1

ID | Description | DimensionType 
------------------------------------------- 
101 |  Row1  |  1 
102 |  Row2  |  1 
103 |  Row3  |  1 
104 |  Row4  |  1 
105 |  Col1  |  2 
106 |  Col2  |  2 
107 |  Col3  |  2 
108 |  Col4  |  2 

在上表中DimensionType表示描述是行還是列。 DimensionType = 1表示rowDimensionType = 2表示column。是

存儲在DB的值如下

表T2

ID | T1R | T1C | Value 
---------------------------------- 
1001 | 101 | 105 | 10 
1002 | 101 | 106 | 20 
1003 | 101 | 107 | 30 
1004 | 101 | 108 | 40 
1005 | 102 | 105 | 50 
1006 | 102 | 106 | 60 
1007 | 102 | 107 | 70 
1008 | 102 | 108 | 80 
. 
. 
. 
an so on. 

祝以下形式來檢索數據。

Row | C1 | Value | C2 | Value | C3 | Value | C4 | Value | 
-------------------------------------------------------------------------------------------- 
     |   |   |   |   |   |   |   |   | 
    Row1 | Col1 | 10 | Col2 | 20 | Col3 | 30 | Col4 | 40 | 
    Row2 | Col1 | 50 | Col2 | 60 | Col3 | 70 | Col4 | 80 | 
    Row3 | Col1 | 90 | Col2 | 100 | Col3 | 110 | Col4 | 120 | 
    Row4 | Col1 | 130 | Col2 | 140 | Col3 | 150 | Col4 | 160 | 
     |   |   |   |   |   |   |   |   | 

需要編寫一個可以以上述格式(在MSSQL中)打印數據的查詢。如果檢索可以進一步優化,這將是更有幫助,即形式

Row | Col1 | Col2 | Col3 | Col4 | 
-------------------------------------------------- 
     |   |   |   |   | 
    Row1 |  10 | 20 | 30 | 40 | 
    Row2 |  50 | 60 | 70 | 80 | 
    Row3 |  90 | 100 | 110 | 120 | 
    Row4 | 130 | 140 | 150 | 160 | 
     |   |   |   |   | 

在此先感謝!

+0

請問有永遠只是八列還是列可以無限增加?這只是一個交叉表挑戰,通常在UI中最好解決,而不是數據庫。 –

+0

不可以有任何數量的列...並且UI中的映射尚未完成... UI的結果將在2個表的幫助下實現。 – SohamC

+0

我看不到'Row1'和'Col1'之間的關係。我認爲'T2'設計是不對的。相反,它必須是:'ID | T1IDRow | T1IDCol |價值「或類似的東西。 – valex

回答

0

未經檢驗的,但嘗試了這一點(我沒有MS SQL在我的面前,並在其至少一年沒有工作,所以這段代碼一味寫):

select t2id, t2t1r, t2t1c, rdesc, 
    STUFF((SELECT ', ' + Value from t ttemp where ttemp.t2t1r = t.t2t1r FOR XML PATH('')), 1, 2, '') as ConcatenatedValues, 
    STUFF((SELECT ', ' + cdesc from t ttemp where ttemp.t2t1r = t.t2t1r FOR XML PATH('')), 1, 2, '') as cdescs, 
from 
(select T2.ID as t2id, T2.T1R as t2t1r, T2.T1C as t2t1c, Value, row.Description as rdesc, col.Description as cdesc 
from T1 join T2 row 
on T1.ID = row.T1R and row.DimensionType = 1 
join T2 col 
on T1.ID = col.T1C and col.DimensionType = 2) t