2014-03-26 30 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