select aa.*,ifnull(bb.cc,0) from (select * from (select distinct T from tbl) a, (select distinct S from tbl) b) aa left join (select T,S,count(1) cc from tbl group by T,S) bb on aa.T=bb.T and aa.S=bb.S;