i have a problem when counting and grouping data from 2 column on single table.
id, price, user_1, user_2 id,价格,user_1,user_2
001 500 bergkamp cech<br>
002 100 cech ljungberg<br>
003 200 viera henry<br>
004 300 bergkamp pires<br>
005 200 lauren bergkamp<br>
SELECT
user_1,user_2,
count(user_1) as total1,
count(user_2) as total2
FROM
sales
group by user_1 and user_2
results with not what i want,
bergkamp 3<br>
henry 1<br>
cech 2<br>
ljungberg 1<br>
lauren 1<br>
pires 1<br>
viera 1<br>
Any help will be so appreciated, thanks
Put both user columns into one with a UNION. Then group by that temp table result and count the names
select user_name, count(*)
from
(
SELECT user_1 as user_name FROM sales
union all
SELECT user_2 FROM sales
) tmp
group by user_name
You can use a UNION
:
SELECT t.user, COUNT(*) AS total
FROM
(
SELECT user_1 AS user
FROM sales
UNION ALL
SELECT user_2
FROM sales
) t
GROUP BY t.user
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.