2014-03-26 17 views
0

请帮我下面的查询SQL查询来获取该组的唯一项目

Group1 Group 2 Group2_Value 
-------------------------------------- 
x   a   1 
y   a   6 
g   a   5 
y   b   3 
g   b   1 
x   c   7 
g   d   9 
g   d   5 
g   e   2 
g   e   2 

我们有3个值组别1 X,Y,G与G作为最高优先级,x是从上面记录最低设置我想写一个查询或SP,它将检查每个唯一Group2(a,b,c,d,e)返回具有最高优先级Group1的行,例如:对于组2值“a”返回行 第1组值为g,第2组值为“c”则返回“x”。另外,如果对于group1“g”,我们有2个条目与不同的Group2_Value,则不返回任何东西 否则返回单个唯一行。

所以结果应该是这样的:

Group1 Group 2 Group2_Value  
-------------------------------------- 
g   a   5 
g   b   1 
x   c   7 
g   e   2 

回答

0

这将产生所需的输出,希望它有助于:

with xxx as (
    select *, 
    row_number() over(partition by group2 order by case group1 when 'g' then 1 when 'y' then 2 else 3 end) as rn 
    from #t 
) 
select group1, group2, max(group2_value) 
from xxx 
group by group1, group2 
having count(*) = 1 
and max(rn) = 1 

union all 

select group1, group2, group2_value 
from xxx 
group by group1, group2, group2_value 
having count(*) > 1 

可能不是最有效的方式,但是,却很难说没有更多信息。

+0

这有助于给我一些建议。 – Piyush

0

对不起后期的帖子,我在休息时开始了这段时间,并被取消。

首先,让我们用你的数据创建一个测试环境。

-- Just playing 
use tempdb; 
go 

-- Create a test table 
create table test 
(
    group1 varchar(4), 
    group2 varchar(4), 
    group2_val int 
); 
go 

-- Add data 
insert into [test] values 
('x','a','1'), 
('y','a','6'), 
('g','a','5'), 
('y','b','3'), 
('g','b','1'), 
('x','c','7'), 
('g','d','9'), 
('g','d','5'), 
('g','e','2'), 
('g','e','2'); 
go 

-- Show data 
select * from [test]; 
go 

其次,我用三个常见的表达式解决了它。每一个建立在彼此之上。

-- Raw data with rank 
with cteRawData 
as 
(
    select group2, group1, group2_val, 
    rank() over 
    (
    partition by group2 order by 
    case group1 
     when 'g' then 1 
     when 'y' then 2 
     when 'x' then 3 
     else 0 
    end 
    ) as drank 
    from [test] 
), 
-- Get distinct topmost rank 
cteRankData as 
(
    select distinct group2, group1, group2_val 
    from cteRawData where drank = 1 
), 
-- Find all singleton records 
cteRankCount as 
(
    select group2, group1 
    from cteRankData 
    group by group2, group1 
    having count(*) = 1 
) 
-- Return the results of a inner join 
select a.group1, a.group2, a.group2_val 
from 
cteRankData a inner join cteRankCount b 
on a.group2 = b.group2 and a.group1 = b.group1 

最后但并非最不重要的,预期的结果。

enter image description here