2011-06-01 48 views
1

如何轉變格式的基礎上,在「Col1中」 讓值表中的初始表的內容是支點SQLSERVER

Col1 Col2 Cnt  color 
---------------------------- 
1  1  5  green 
1  2  0  blue 
1  3  7  red 
2  1  0  gray 
2  2  10  yellow 
2  3  8  orange 

INTO的格式如下

c11 d11 e11 color11 c12 d12 e12 color12 c13 d13 e13 color13 
------------------------------------------- ----------------------- 
1 1 5 green  1 2 0 blue  1 3 7 red 
2 1 0 gray  2 2 10 yellow 2 3 8 orange 

表該查詢用於生成報告的數據集。在那裏我繪製了每個x,y座標的氣泡圖。

「c11 d11 e11 c12 d12 e12 c13 d13 e13」是新數據集中的列名。由於列可能動態變化,我引用這種方式。

我用顏色來繪製每個泡沫值

能有一個人請在此查詢幫助的顏色?

+0

你爲什麼要這樣?你能解釋一下情況嗎? – Pankaj 2011-06-01 15:05:42

+1

乍一看似乎有些缺失的數據。 c11,d11從哪裏來? – tofutim 2011-06-01 15:06:42

+0

在SQL 2005及以上版本中有Pivot運算符 http://msdn.microsoft.com/en-us/library/ms177410.aspx – Magnus 2011-06-01 15:15:06

回答

0

我不認爲PIVOT解決方案是你真正的追求。相反,你可以做以下

WITH TestData AS 
(
SELECT 1 Col1, 1 Col2, 5 Cnt, 'green' color 
UNION SELECT 1 , 2 , 0 Cnt, 'blue' 
UNION SELECT 1 , 3 , 7 Cnt, 'red' 
UNION SELECT 2 , 1 , 0 Cnt, 'gray' 
UNION SELECT 2 , 2 , 10 Cnt, 'yellow' 
UNION SELECT 2 , 3 , 8 Cnt, 'orange' 

) 
SELECT 
    t1.col1 c11 , 
    t1.col2 d11 , 
    t1.cnt e11, 
    t1.color color11, 
    t2.col1 c12 , 
    t2.col2 d12 , 
    t2.cnt e12, 
    t2.color color12 , 
    t3.col1 c13 , 
    t3.col2 d13 , 
    t3.cnt e13, 
    t3.color color13 


FROM 
    TestData t1 
    inner join TestData t2 
    ON t1.Col1 = t2.Col1 
    inner join TestData t3 
    ON t1.Col1 = t3.Col1 
where t1.Col2 = 1 
    and t2.Col2 = 2 
    and t3.Col2 = 3 

,輸出這個

c11 d11 e11 color11 c12 d12 e12 color12 c13 d13 e13 color13 
--- --- --- ------- --- --- --- ------- --- --- --- ------- 
1 1 5 green 1 2 0 blue 1 3 7 red 
2 1 0 gray 2 2 10 yellow 2 3 8 orange 

(2 row(s) affected) 

我的猜測是,你可能需要動態地生成這個SQL在您的解決方案,而不是靜態的解決方案,我有。

+0

感謝您的信息。我將致力於創建動態sql來生成數據集。因爲我在博客中讀到關於使用PIVOT將行轉換爲列的使用,我一直在尋找使用PIVOT的解決方案。再次感謝您花時間詳細示例。 – Thiyanesh 2011-06-02 02:46:52

+0

我用動態查詢實現了它。謝謝您的幫助 – Thiyanesh 2011-06-03 04:10:56