在这种情况下,我该如何查询键值对?

时间:2015-02-26 17:18:49

标签: sql sql-server subquery

我正在尝试查询2个单独的键值对,如下所示: AttributeTable包含3列[感兴趣的]

ID       KeyColumn     ValueColumn
12345    Sector        Sector 1
12345    Group         Group X

我需要查询以获得以下输出:

ID      Sector     Group
12345   Sector 1   Group X

这是我到目前为止所做的:

SELECT ID, (SELECT VALUECOLUMN WHERE KEYCOLUMN = 'Sector') as Sector,(SELECT VALUECOLUMN WHERE KEYCOLUMN = 'Group') as Group
FROM AttributeTable 
GROUP BY ID, KEYCOLUMN, VALUECOLUMN

显然,这是错误的,因为它给了我重复[每个ID 3列的每行1行]

我如何才能获得所需的输出?

3 个答案:

答案 0 :(得分:3)

测试数据

DECLARE @TABLE TABLE (ID INT, KeyColumn VARCHAR(10), ValueColumn VARCHAR(10))
INSERT INTO @TABLE VALUES 
(12345    ,'Sector'    ,    'Sector 1'),
(12345    ,'Group'     ,    'Group X')

<强>查询

SELECT * 
FROM @TABLE
        PIVOT (MAX(ValueColumn)
               FOR KeyColumn
               IN ([Sector] , [Group]))p

<强>结果

╔═══════╦══════════╦═════════╗
║  ID   ║  Sector  ║  Group  ║
╠═══════╬══════════╬═════════╣
║ 12345 ║ Sector 1 ║ Group X ║
╚═══════╩══════════╩═════════╝

答案 1 :(得分:1)

如果您需要PIVOT的替代方案,我见过的用于实体 - 属性 - 值表的视图如下所示:

SELECT DISTINCT
    a.ID
    f1.ValueColumn AS "Sector",
    f2.ValueColumn AS "Group"
FROM AttributeTable a
LEFT JOIN AttributeTable f1 ON f1.ID = a.ID AND f1.KeyColumn = 'Sector'
LEFT JOIN AttributeTable f2 ON f2.ID = a.ID AND f2.KeyColumn = 'Group'

等等,每个字段都有一个连接。动态生成它们是一个巨大的痛苦,PIVOT只是稍微好一点,因为它也不是动态的。如果您有理由避免聚合(例如,如果ValueColumnBIT),这可能会有所帮助。

答案 2 :(得分:0)

我认为这会有所帮助。没有支点

SELECT a.ID,Max(decode(a.keycolumn,'Group',a.ValueColumn,null))AS "group",
Max(decode(a.keycolumn,'Sector',a.ValueColumn,null))AS "Sector" 
FROM AttributeTable where KeyColumn in ( 'Group','Sector')
Group by a.id;