-2

假设我们有一个这样的表:

entity_id attribute_name attribute_value
----------------------------------------
0         server         alpha
1         server         beta
0         priority       1
1         priority       2
1         comment        some comment
2         server         gamma

对于 PostgreSQL,将给出以下结果的查询是什么:

server    alpha     beta
priority  1         2

笔记:

  • 我们假设我们只想比较 id 为 0 和 1 的实体。
  • 如果两个实体的属性都不存在,则可以忽略它
4

3 回答 3

1

尝试这个

CREATE TABLE test1(entity_id int,attribute_name varchar(100), attribute_value varchar(100))
insert into test1
VALUES(0,'server','alpha'),
(1,'server','beta'),
(0,'priority','1'),
(1,'priority','2'),
(2,'server','gamma')

;WITH CTE as(
select attribute_name,(select STUFF((select ','+ attribute_value from test1 where entity_id in (0,1) and attribute_name=t1.attribute_name  for XML path('')),1,1,'') ) as colms
from test1 t1
where entity_id in (0,1)
group by attribute_name)

select attribute_name,LEFT(colms,CHARINDEX(',',colms,1)-1) as attr_value1,RIGHT(colms,len(colms)-CHARINDEX(',',colms,1)) as attr_value2 from CTE
order by 1 desc
于 2012-08-13T16:42:53.770 回答
0

这应该在 TSQL 中工作:

SELECT T.attribute_name, A.attribute_value, B.attribute_value
FROM theTable T
CROSS APPLY (
    SELECT T0.attribute_value
    FROM theTable T0
    WHERE T0.entityId = 0 AND T0.attribute_name = T.attribute_name
) A
CROSS APPLY (
    SELECT T1.attribute_value
    FROM theTable T1
    WHERE T1.entityId = 1 AND T1.attribute_name = T.attribute_name
) B

您可以添加更多CROSS APPLYs 以包含更多实体的结果。如果不能保证attribute_value每个 entityId/name 对都有一个,则可以将其替换为(或等效地OUTER APPLY使用INNER/ s)LEFT JOIN

于 2012-08-13T16:25:01.493 回答
0

至少在 MySQL 中有效:

select attr_list.attribute_name, t0.attribute_value, t1.attribute_value
  from (select distinct attribute_name from tbl) as attr_list
  left join tbl as t0 on t0.attribute_name = attr_list.attribute_name 
   and t0.entity_id = 0
  left join tbl as t1 on t1.attribute_name = attr_list.attribute_name 
   and t1.entity_id = 1
于 2012-08-13T16:27:05.353 回答