2017-02-21 40 views
1

我想從子表中計算一些列。我的表結構如下:來自子表的SQL計數

+---+----------+--------+ 
| Pid | Name |Surname | 
+---+----------+--------+ 
| 1 | Per A | D  | 
| 2 | Per B | E  | 
| 3 | Per C | F  
+----+---------+--------+ 

童車

+---+---------+-------------------+------------+-----+ 
| Cid | CName   | School | Sex  | Pid | 
+---+---------+-------------------+------------+-----+ 
| 1 | John   | High  | Man  | 1 | 
| 2 | Alice   | Primary | Woman | 2 | 
| 3 | Mel   | High  | Man  | 3 | 
| 4 | Angelina  | High  | Woman | 2 | 
+----+---------+------------------+------------+-----+ 

所以我想輸出

+---+----------+------+---------+--------+---+--------------+ 
| Pid| PerName | High | Primary | Woman | Man | ChildCount | 
+---+----------+------+---------+--------+-----+------------+ 
| 1 | Per A | 1 | 0  | 0  | 1 | 1   | 
| 2 | Per B | 1 | 1  | 2  | 0 | 2   | 
| 3 | Per C | 1 | 0  | 0  | 1 | 1   | 
+----+---------+------+---------+--------+-----+------------+ 

我怎樣才能得到這個輸出?

我嘗試這種方法,但我有更多的列這樣計算屬於子表。所以我得到緩慢的查詢結果。

select Pid,Name,Surname, 
    (select count(*) from Childs where Persons.Pid=Childs.Pid) ChildCount, 
    (select count(*) from Childs where Persons.Pid=Childs.Pid and School='Primary') Primary 
from Persons 
+0

JOIN表。做一個GROUP BY。 – jarlh

+0

我想只用Pid分組,但SQL想要其他列也像名稱,姓氏等如果在MySQL中沒有問題,但在MSSQL問題 – mbayrak

+0

較新的MySQL版本不會讓你做無效的GROUP BY - 除非在兼容模式。 – jarlh

回答

2

您可以join和有條件聚集做到這一點:

select p.Pid, p.Name, 
     sum(case when c.school = 'High' then 1 else 0 end) as high, 
     sum(case when c.school = 'Primary' then 1 else 0 end) as primary, 
     sum(case when c.sex = 'Man' then 1 else 0 end) as Man, 
     sum(case when c.sex = 'Woman' then 1 else 0 end) as Woman, 
     count(*) as ChildCount 
from persons p left join 
    childs c 
    on p.pid = c.pid 
group by p.Pid, p.Name; 
+0

我想只用Pid分組,並且想要選擇Name,Surname,但是SQL想要其他列也像Name,Surname等因爲相同的名稱。我們怎樣才能做到這一點 – mbayrak

0

試試這個:

select Pid,Name,Surname, 
ifNull((select count(*) from Childs where Persons.Pid=Childs.Pid),0) ChildCount, 
ifNull((select count(*) from Childs where Persons.Pid=Childs.Pid AND School='High' GROUP By Childs.Pid),0) High, 
ifNull((select count(*) from Childs where Persons.Pid=Childs.Pid AND School='Primary' GROUP By Childs.Pid),0) 'primary', 
ifNull((select count(*) from Childs where Persons.Pid=Childs.Pid AND Sex='Woman' GROUP By Childs.Pid),0) Woman, 
ifNull((select count(*) from Childs where Persons.Pid=Childs.Pid AND Sex='Man' GROUP By Childs.Pid),0) Man 

from Persons; 
+0

我也試過這個,但執行速度很慢 – mbayrak