我有一个Server 2008 R2表,其架构如下
DECLARE @AttributeTable TABLE
(
Code1 nvarchar(50),
Value1 nvarchar(50),
Code2 nvarchar(50),
Value2 nvarchar(50),
Stock int
);其价值如下:
Color, Red, Size, Large, 15
Color, Blue, Size Large, 5
Size, Large, Color, Green, 4我正在寻找一种方法来重新排序每一行的列(动态地,而不是在表本身中),这样查询的结果将是
Color, Red, Size, Large, 15
Color, Blue, Size Large, 5
Color, Green, Size, Large, 4但是,我想不出有什么办法可以做到这一点,而不需要创建一个.NET函数,这看起来有点过火了。
我承认这是一个失败的架构,但是模式属于第三方ERP,我无法更改。
最后,如果有人对这个问题的标题有一个好主意,请随时编辑(或者评论,我会修改的)
编辑:
这个示例所基于的实表有6个不同的键值对,而不是两个,并且' code‘值是动态的(当前数据库有大约45个不同的代码值)。
发布于 2012-07-08 04:42:08
这将处理3个泛型代码/值对,并正确地重新排序输出。这显然不是完美的,但它解决了我的需求。
第一个查询查找代码值,并将它们按表中第一个项的顺序排列。将其扩展为函数或存储过程并按顺序传递并不困难。
第二个查询使用PaulBailey的解决方案来正确排序这两对。
DECLARE @ItemCode nvarchar(50) = 'ITEM-000001'
DECLARE @Code1 nvarchar(50)
DECLARE @Code2 nvarchar(50)
DECLARE @Code3 nvarchar(50)
SELECT TOP 1
@Code1 = ii.AttributeCode1
, @Code2 = ii.AttributeCode2
, @Code3 = ii.AttributeCode3
FROM @AttributeTable ii
WHERE ii.ItemCode = @ItemCode
SELECT ii.ItemCode
, @Code1 as [AttributeCode1]
, CASE WHEN ii.AttributeCode1 = @Code1 THEN ii.Attribute1
WHEN ii.AttributeCode2 = @Code1 THEN ii.Attribute2
WHEN ii.AttributeCode3 = @Code1 THEN ii.Attribute3
ELSE null END as [Attribute1]
, @Code2 as [AttributeCode2]
, CASE WHEN ii.AttributeCode1 = @Code2 THEN ii.Attribute1
WHEN ii.AttributeCode2 = @Code2 THEN ii.Attribute2
WHEN ii.AttributeCode3 = @Code2 THEN ii.Attribute3
ELSE null END as [Attribute2]
, @Code3 as [AttributeCode3]
, CASE WHEN ii.AttributeCode1 = @Code3 THEN ii.Attribute1
WHEN ii.AttributeCode2 = @Code3 THEN ii.Attribute2
WHEN ii.AttributeCode3 = @Code3 THEN ii.Attribute3
ELSE null END as [Attribute3]
FROM @AttributeTable ii
WHERE ii.ItemCode = @ItemCode
ORDER BY [AttributeCode1], [Attribute1]
, [AttributeCode2], [Attribute2]
, [AttributeCode3], [Attribute3]发布于 2012-07-03 06:27:49
如果该表像您显示的那样简单,则相对简单:
SELECT
'Color',
CASE WHEN Code1 = 'Color' THEN Value1 ELSE Value2 END,
'Size',
CASE WHEN Code1 = 'Size' THEN Value1 ELSE Value2 END,
Stock
FROM
@AttributeTablehttps://stackoverflow.com/questions/11305485
复制相似问题