1

我创建了以下选择语句:

SELECT     x.Code, y.AttributeCode, y.Value
FROM         x INNER JOIN
                      y ON x.Id = y.ItemCodeId
WHERE  (AttributeCode = 'Length' or AttributeCode = 'Width' or AttributeCode = 'Height')

结果显示如下:

Code    AttributeCode   Value
1000165 Width              4
1000165 Length           19.5
1000165 Height            3.8
1000173 Length             3
1000173 Height             8
1000173 Width              5

我希望它们显示如下:

100165 Width 4 Length 19.5 Height 3.8
100173 Width 5 Length 3    Height 8

如果这是重复,我深表歉意,但我查看了其他几个答案来尝试回答这个问题(MS SQL 对我来说是新的,所以我在搜索时可能没有使用正确的语言)。

4

2 回答 2

3

啧啧啧,有人去EAV(Entity-Attribute-Value)了。无论如何,在这种情况下,可以使用PIVOT将一组有限的值切回到列中。它是标准 SQL 的 SQL Server 扩展 - 但对于这种情况,它是一个非常有用的扩展:

PIVOT 通过将表达式中的一列中的唯一值转换为输出中的多列来旋转表值表达式,并在最终输出中需要的任何剩余列值上执行聚合。

这是一个显示 PIVOT的SQL Fiddle :

-- SETUP
create table x (entity int, attribute varchar(20), value float);
insert into x (entity, attribute, value) values 
  (1000165, 'Width', 4),
  (1000165, 'Length', 19.5),
  (1000165, 'Height', 3.8),
  (1000173, 'Length', 3),
  (1000173, 'Height', 8),
  (1000173, 'Width', 5)

-- QUERY
SELECT pvt.*
FROM (SELECT entity, attribute, value FROM x) AS src
PIVOT (
  -- Have to use an aggregate, but we have multiplicity of one as
  -- presented so that's not an issue: MAX of any single value is itself.
  -- Note that there is an implicit GROUP BY on columns NOT in
  -- the aggregate ([value]) or used for the pivot ([attribute]) which
  -- leaves only [entity] as the grouping column.
  MAX(value)
  FOR attribute IN ([Width], [Length], [Height])
  ) AS pvt

-- RESULT
ENTITY      WIDTH   LENGTH  HEIGHT
1000165     4       19.5    3.8
1000173     5       3       8

PIVOT ( src) 的输入和 PIVOT 的结果可以根据需要进行过滤或合并。使用 PIVOT 需要注意的唯一真正“问题”是意外携带一个额外的(和错误预期的)分组列

于 2013-07-26T23:36:17.040 回答
0
SELECT x.Code, a.AttributeCode, a.Value, b.AttributeCode, b.Value, c.AttributeCode, c.Value
FROM x
INNER JOIN y a ON x.Id = a.ItemCodeId
INNER JOIN y b ON x.Id = b.ItemCodeId
INNER JOIN y c ON x.Id = c.ItemCodeId
WHERE (a.AttributeCode = 'Width') and (b.AttributeCode = 'Length') and (c.AttributeCode = 'Height') 
于 2013-07-26T23:23:53.147 回答