2016-06-25 223 views
0

我有一個表:複雜查詢

Number | Name 
__________________ 

100  | A 
101  | B 
102  | C 
103  | D 
104  | E 
..................  
105  | F 
106  | G 
108  | I 
109  | J 
..................  
110  | K 
111  | L 
114  | O 
.................. 
115  | P 
116  | Q 
...  | ... 

Number 0。4和其他字符是相同的是在一組,而那些有5間最後一個字符的所有行.. 9在另一個組中。這類團體在此表:

Group 100 
    Group 105 
    Group 110 
    Group 115 
    Group ... 

我怎樣才能找到不全組(缺少的成員)?

對於以上(顯示爲一個例子)表,結果是:

Group 105 [missing members: 107] 
    Group 110 [missing members: 112,113] 
+0

你想只用SQL來產生這樣的輸出嗎? – YakovL

回答

0

這裏是你如何能做到這

-- sample data 
; with tbl as 
(
    select Number = 100 union all 
    select Number = 101 union all 
    select Number = 102 union all 
    select Number = 103 union all 
    select Number = 104 union all 
    select Number = 105 union all 
    select Number = 106 union all 
    select Number = 108 union all 
    select Number = 109 union all 
    select Number = 110 union all 
    select Number = 111 
), 
-- number tables (here you only required 0 to 4 as you are grouping by 5) 
num as 
(
    select n = 0 union all 
    select n = 1 union all 
    select n = 2 union all 
    select n = 3 union all 
    select n = 4 
) 
-- the query 
select [Group] = t.Number/5 * 5, misisng = max(stuff(m.missing, 1, 1, '')) 
from tbl t 
    cross apply 
    (
     select ',' + convert(varchar(10), (t.Number/5 * 5) + n) 
     from num 
     where not exists 
      (
       select * 
       from tbl x 
       where x.Number = (t.Number/5 * 5) + n 
      ) 
     order by n 
     for xml path('')    
    ) m (missing) 
where m.missing is not null 
group by t.Number/5 * 5 

- 如果你想在mssing使用此查詢no in separate lines - 查詢 選擇不同[Group] = t.Number/5 * 5,m.missing from tbl t 交叉應用 ( 選擇缺失=(t.Number/5 * 5)+ n的NUM 其中不存在 ( SELECT * 從TBL X 其中x.Number =(t.Number/5 * 5)+ N ) )米 其中m.missing不爲空

+0

它不起作用! – daiphuniadea

+0

@daiphuniadea,請詳細說明什麼不起作用? – Squirrel

+0

對不起,它工作正常。我怎麼能得到這個結果在單獨的記錄,平均組110在兩個記錄。謝謝 – daiphuniadea

0

它工作正常。

Group 105 [missing members: 107] 
Group 110 [missing members: 112,113] 

我怎麼能得到這個結果在單獨的記錄,平均組110在兩個記錄。 是這樣的:

Group 105 [missing member: 107] 
Group 110 [missing member: 112] 
Group 110 [missing member: 113]