SQL Query并排比较存储在同一数据库表中的属性

时间:2012-08-13 16:00:30

标签: sql postgresql join

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

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的实体。
  • 如果两个实体都没有属性,则可以忽略

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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 APPLY以包含更多实体的结果。如果不保证每个entityId / name对都有attribute_value,则可以将其替换为OUTER APPLY(或等效地使用INNER / LEFT JOIN

答案 2 :(得分: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