2016-12-28 21 views
2

我需要根據另一個表中的特定標準創建個人表。與數據相關的記錄被組合在一起(基於彼此的距離)。我有另一個填充了特定代碼的字段。查詢結果應該只包括從所有組中的所有屬性沒有一定的代碼(在這種情況下,2和3):查詢以省略在屬性中具有特定值的一個記錄的整個組

|groupid | id | code | stuff | 
----------------------------------| 
| a | 1 | 1 | data | 
| a | 2 | 1 | data | 
| b | 3 | 1 | data | 
| b | 4 | 2 | data | 
| c | 5 | 1 | data | 
| c | 6 | 3 | data | 
| d | 7 | 2 | data | 
| d | 8 | 4 | data | 
| e | 9 | 4 | data | 
| e | 10 | 4 | data | 
----------------------------------- 

在這種情況下,我需要創建一個包含所有的個人表記錄和屬性,其中結果如下:

|groupid | id | code | stuff | 
----------------------------------| 
| a | 1 | 1 | data | 
| a | 2 | 1 | data | 
| e | 9 | 4 | data | 
| e | 10 | 4 | data | 
----------------------------------- 

由於代碼2和3是不可靠的研究中,包含任何這些值的整個組不能被分析。查詢應該是select *,因爲我需要所有的屬性(有4個以上)。謝謝。

回答

2
select * 
from your_table t1 
where not exists (
    select 1 from your_table t2 
    where t1.group = t2.group 
    and t2.code in (2, 3) -- exclusion list here 
); 
1

你描述它的英文

差不多
Select * from table a 
Where Not exists 
    (Select * from table 
    where groupid = a.groupId 
     and code in (2,3)) 

測試用例:

declare @t table 
(groupid char(1) not null, 
id int not null, code int not null, 
stff varchar(10) not null) 
insert @t(groupid, id, code, stff)values 
('a', 1, 1, 'data'), 
('a', 2, 1, 'data'), 
('b', 3, 1, 'data'), 
('b', 4, 2, 'data'), 
('c', 5, 1, 'data'), 
('c', 6, 3, 'data'), 
('d', 7, 2, 'data'), 
('d', 8, 4, 'data'), 
('e', 9, 4, 'data'), 
('e', 10, 4, 'data') 
select * from @t 

Select * from @t a 
Where Not exists 
    (Select * from @t 
    where groupid = a.groupId 
     and code in (2,3)) 

結果:

a 1 1 data 
    a 2 1 data 
    e 9 4 data 
    e 10 4 data 
+0

確切的我的:) – GurV

0

這可以通過分析函數來完成,所以只讀基表一次 - 導致更好的性能。這幾乎是創建分析函數的地方。

如果你有太多的列,不想輸入姓名兩次(儘管這的「最佳實踐」),你可能select *中,如果你不介意保持ct列外層查詢(所有值都將爲0),在內部查詢中,您可能select <table_name>.*, count(....)...。在內部查詢中,您需要必須符合*的表名,因爲您還選擇了另一個「列」ct

with 
    test_data (groupid, id, code, stuff) as (
     select 'a', 1, 1, 'data' from dual union all 
     select 'a', 2, 1, 'data' from dual union all 
     select 'b', 3, 1, 'data' from dual union all 
     select 'b', 4, 2, 'data' from dual union all 
     select 'c', 5, 1, 'data' from dual union all 
     select 'c', 6, 3, 'data' from dual union all 
     select 'd', 7, 2, 'data' from dual union all 
     select 'd', 8, 4, 'data' from dual union all 
     select 'e', 9, 4, 'data' from dual union all 
     select 'e', 10, 4, 'data' from dual 
    ) 
-- end of test data; the solution (SQL query) begins below this line 
select groupid, id, code, stuff 
from (select groupid, id, code, stuff, 
       count(case when code in (2, 3) then 1 end) 
        over (partition by groupid) as ct 
     from test_data 
     ) 
where ct = 0 
order by groupid, id -- order by is optional 
; 

GROUPID ID CODE STUFF 
------- ---- ------ ----- 
a   1  1 data 
a   2  1 data 
e   9  4 data 
e   10  4 data 

4 rows selected. 
相關問題