2016-10-08 41 views
0

我有一個表像下:選擇和計數,其中結果是在其他地方

ID | Name    | Type  | State   | County 
------------------------------------------------------------------- 
1 | Rheinland-Pfalz | State  | Rheinland-Pfalz | NULL 
2 | Trier    | City  | Rheinland-Pfalz | NULL 
3 | Alzey-Worms  | County  | Rheinland-Pfalz | Alzey-Worms 
4 | Alzey    | City  | Rheinland-Pfalz | Alzey-Worms 
5 | Worms    | City  | Rheinland-Pfalz | Alzey-Worms 
6 | Lorem    | County  | Rheinland-Pfalz | Lorem 
7 | Ipsum    | City  | Rheinland-Pfalz | Lorem 

現在我想獲得國家「萊茵蘭 - 普法爾茨」及其包括城市和所有countie自由城市內所有的縣。

祝願結果:

ID | Name   | Type  | Included   
------------------------------------------------------------------- 
2 | Trier   | City  | NULL 
3 | Alzey-Worms | County  | 2 
6 | Lorem   | County  | 1 

我的查詢:

select a.id, a.name, a.type, 
       (select count(*) from data where a.type="city" AND b.county=a.county) as included 
       from data as a, data as b 
       WHERE a.location_type='county' AND a.state = 'Rheinland-Pfalz' OR a.type='city' AND a.gmap_area1 = 'Rheinland-Pfalz' AND a.county IS NULL 
       order by a.name asc 

我的結果:

ID | Name   | Type  | Included   
------------------------------------------------------------------- 
3 | Alzey-Worms | County  | 0 
3 | Alzey-Worms | County  | 0 
3 | Alzey-Worms | County  | 0 
3 | Alzey-Worms | County  | 0 
3 | Alzey-Worms | County  | 0 

....等等

+0

請問上面的查詢工作? –

+0

@ AT-2016:不,我用結果更新了帖子... – chack

回答

1

不要羞於用括號

SELECT 
    a.id, 
    a.name, 
    a.type, 
    (SELECT COUNT(*) FROM data 
     WHERE type='city' AND county=a.county) AS included 
FROM data AS a 
WHERE 
    a.state='Rheinland-Pfalz' AND 
    (a.type='county' OR (a.type='city' AND a.county IS NULL)); 
+0

真棒!非常感謝!不是很遠:) – chack

0

一個方式,你可以嘗試小組條款 - 未經測試:

select count(*) from data where type in ('state','County') where 
    state = 'Rheinland-Pfalz' group by type,state; 

另外要考慮的是ID或詳細的現場級值將不會出現在數

+0

這個計數是正確的,但我想要結果中的計數和詳細字段... – chack

+0

嘗試在他們的選擇雄蕊和組中添加字段 - 不應該包含像id的詳細級別字段 – Ltaylor

+0

...選擇姓名,類型,計數(*)...按名稱分組,類型 – Ltaylor