Fetching columns from 2 different tables and group by 2 different columns

时间:2017-06-15 10:11:23

标签: mysql

SELECT aSites,count(MessageId) from messages group by aSites
UNION
SELECT bSites,count(callId) from calls group by bSites

I want 2 columns as output, 1 for messages and other for calls and group it by aSites and bSites (aSites and BSites has some common names).

What am I doing wrong?

2 个答案:

答案 0 :(得分:0)

SELECT aSites,bSites,sum(asitecount) asitecount,sum(bsitecount) bsitecount from
(
    SELECT aSites,null bSites,count(MessageId) asitecount,0 bsitecount from messages group by aSites
    UNION
    SELECT null aSites,bSites,0 asitecount,count(callId) bsitecount, from calls group by bSites
)Z

Try above code. Hope this will help you.

答案 1 :(得分:0)

If you want to group all elements in the first column (not distinguishing between aSites and bSites you need to re-group the results. Try with:

SELECT a.sites, sum(a.count) FROM 
(
SELECT aSites as sites,count(MessageId) AS count FROM messages GROUP BY sites
UNION
SELECT bSites as sites,count(callId) AS count FROM calls GROUP BY sites
) a
GROUP BY a.sites