2011-06-01 50 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