sql查询以获取组的唯一条目

时间:2014-03-26 17:28:30

标签: sql-server stored-procedures

请帮我解决以下问题

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个值为Group1 x,y,g,其中g为最高优先级,x为上述记录集中最低的我想写一个查询或SP,它将检查每个唯一的Group2(a,b,c) ,d,e)返回具有最高优先级Group1的行,例如:对于组2值" a"返回行 组1的值为g,组2的值为#34; c"用" x"返回一个。如果对于group1" g"我们有2个不同Group2_Value的条目然后不返回任何东西 否则返回单一的唯一行。

所以结果应该是:

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

2 个答案:

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

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

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