如何将未知行数转换为列

时间:2014-03-19 16:56:38

标签: sql sql-server sql-server-2008

我需要转换此表

id | fieldname | length | fieldtext
---|-----------|--------|--------------
1  | field1    |   12   | sadsadasdfaf
2  | field1    |   10   | asdfasdasd
3  | field1    |   14   | afgsdfgsdgssdf
4  | field1    |   15   | asdfafaaasdfasf
5  | field2    |   10   | afgsagsaga
6  | field2    |   4    | asdf
7  | field2    |   12   | sadfasfsdafg
8  | field3    |   12   | asdsadfgsdas
9  | field3    |   5    | xaadd 

到这个表

id |fieldname | s_text        | m_text       | l_text         | vl_text
---|----------|---------------|--------------|----------------|----------
1  | field1   | asdfasdasd    | sadsadasdfaf | afgsdfgsdgssdf | asdfafaaasdfasf
2  | field2   | NULL          | asdf         | afgsagsaga     | sadfasfsdafg  
3  | field3   | NULL          | NULL         | xaadd          | asdsadfgsdas  

根据字段的长度,新文本列将填充原始表中的fieldtext。最长的文本应该转到vl_text(verylarge_text),最小的文本应该转到s_text(小文本)。

如果有< 4个文本,较小的textcolumns将设置为NULL。

我知道我可以使用pivot功能,但我查看的所有示例都使用字段中的文本作为列名。有没有办法创建一个能给我想要的结果的SELECT语句?这在SQL中是否可行,或者我是否必须编写一个小程序来实现这一目标?

我正在使用SQL Server 2008。

原始表架构:

CREATE TABLE [dbo].[texttable](
    [id] [int] NOT NULL,
    [fieldname] [varchar](50) NOT NULL,
    [length] [int] NOT NULL,
    [fieldtext] [varchar](50) NOT NULL
) 

INSERT INTO [dbo].[texttable] (id, fieldname, length, fieldtext) values (1, 'field1', 12, 'sadsadasdfaf');
INSERT INTO [dbo].[texttable] (id, fieldname, length, fieldtext) values (2, 'field1', 10, 'asdfasdasd');
INSERT INTO [dbo].[texttable] (id, fieldname, length, fieldtext) values (3, 'field1', 14, 'afgsdfgsdgssdf');
INSERT INTO [dbo].[texttable] (id, fieldname, length, fieldtext) values (4, 'field1', 15, 'asdfafaaasdfasf');

INSERT INTO [dbo].[texttable] (id, fieldname, length, fieldtext) values (5, 'field2', 10, 'afgsagsaga');
INSERT INTO [dbo].[texttable] (id, fieldname, length, fieldtext) values (6, 'field2', 4, 'asdf');
INSERT INTO [dbo].[texttable] (id, fieldname, length, fieldtext) values (7, 'field2', 12, 'sadfasfsdafg');

INSERT INTO [dbo].[texttable] (id, fieldname, length, fieldtext) values (8, 'field3', 12, 'asdsadfgsdas');
INSERT INTO [dbo].[texttable] (id, fieldname, length, fieldtext) values (9, 'field3', 5, 'xaadd');

新表架构:

CREATE TABLE [dbo].[newtexttable](
   [id] [int] NOT NULL,
   [fieldname] [varchar](50) NOT NULL,
   [s_text] [varchar](50),
   [m_text] [varchar](50) ,
   [l_text] [varchar](50) ,
   [vl_text] [varchar](50) 
)

INSERT INTO [dbo].[newtexttable] (id, fieldname, s_text, m_text, l_text, vl_text) values (1, 'field1', 'asdfasdasd', 'sadsadasdfaf', 'afgsdfgsdgssdf', 'asdfafaaasdfasf');
INSERT INTO [dbo].[newtexttable] (id, fieldname, s_text, m_text, l_text, vl_text) values (2, 'field2', NULL, 'asdf', 'afgsagsaga','sadfasfsdafg');
INSERT INTO [dbo].[newtexttable] (id, fieldname, s_text, m_text, l_text, vl_text) values (3, 'field3', NULL, NULL, 'xaadd', 'asdsadfgsdas');

0 个答案:

没有答案