2012-11-26 99 views
2

我想加入兩個或多個具有group by子句的select語句,但它不起作用。使用Group By子句呈現2條select語句

SELECT COUNT(`rank`) AS rank1,sitename 
FROM `larrdb_ranking` 
INNER JOIN larrdb_site_list USING (sid) 
WHERE rank=1 
GROUP BY sitename 
UNION 
SELECT COUNT(`rank`) AS rank2 ,sitename 
FROM `larrdb_ranking` 
INNER JOIN larrdb_site_list USING (sid) 
WHERE rank=2 
GROUP BY sitename 

所有我所得到的是第一個發言的工作,但第二個語句沒有。我沒有得到秩2選擇

UPDATE:

UNION ALL沒有按」將不起作用太:

SELECT COUNT(`rank`) AS rank1,sitename 
FROM `larrydb_ranking` 
INNER JOIN larrydb_site_list USING (sid) 
WHERE rank=1 
GROUP BY sitename 
UNION ALL 
SELECT COUNT(`rank`) AS rank2 ,sitename 
FROM `larrydb_ranking` 
INNER JOIN larrydb_site_list USING (sid) 
WHERE rank=2 
GROUP BY sitename 

column..rank2沒有被呈現

+0

你可以指定以哪種方式你希望你的輸出,並還與數據 –

回答

1

試試這個:

SELECT SUM(IF(rank=1, 1, 0)) AS rank1, SUM(IF(rank=2, 1, 0)) AS rank2,sitename 
FROM `larrydb_ranking` 
INNER JOIN larrydb_site_list USING (sid) 
GROUP BY sitename 
+0

指定表的結構如何,awesome..seems工作 – BlackFire27