SQL查询以选择属性的并集

时间:2014-10-07 10:45:40

标签: sql sql-server oracle

有一张桌子:

ID    INDEX  PROPERTY  VALUE
-----------------------------
1      1      p1        v1
2      1      p3        v3
3      2      p2        v2
4      2      p3        v3a
5      3      p1        v1a
6      3      p2        v2a
7      3      p3        v3b

我需要选择所有PROPERTY的并集,其中INDEX = 1或INDEX = 2(INDEX = 3不在intereset中)。同时,如果INDEX = 2,则应从INDEX = 2中选择VALUE of PROPERTY - 从INDEX = 1,即我期望结果集中有3个属性:p1 = v1,p2 = v2,p3 = v3a

如何在不使用完全外连接的情况下为此类任务编写SQL查询(SQL Server和Oracle)?

2 个答案:

答案 0 :(得分:0)

我明白了。您希望结果集对于每个Property只有一行,仅来自索引1和2,当存在重复时,优先级为2。

您可以使用窗口功能执行此操作:

select t.*
from (select t.*,
             row_number() over (partition by property order by index desc) as seqnum
      from table t
      where index in (1, 2)
     ) t
where seqnum = 1;

您也可以使用union all

执行此操作
select *
from table t
where index = 2
union all
select *
from table t
where index = 1 and
      not exists (select 1 from table t2 where t2.property = t.property and t2.index = 2);

顺便说一句,index是列的糟糕名称,因为它是一个保留字。

答案 1 :(得分:0)

添加建议的答案以选择所有PROPERTY的联合,您可以将其写为:

;with cte as
(
    select row_number() over ( partition by PROPERTY order by [INDEX] desc) 
    as rownum,
    PROPERTY,VALUE
    from Test 
    where [INDEX] in (1,2)
 )
SELECT top 1 STUFF(
               (SELECT      ',' + cte1.PROPERTY + '=' + cte1.VALUE
               FROM      cte AS cte1
               WHERE      cte1.rownum = cte.rownum 
               FOR XML PATH('')), 1, 1, '') AS PROPERTY

FROM cte
where rownum = 1

DEMO