[英]How to use subqueries to combine columns
I have a table(mainusertb) as follows,我有一个表(mainusertb)如下,
select * from mainusertb order by UserID asc;
UserID Username Status
1 Mike Active
2 Ann Active
3 Michel Active
4 John Active
5 Anonymous Active
Further I have some other table(emprevntb):此外,我还有一些其他表(emprevntb):
Subusers Revenue Hour
Mike_1 32 3
Mike_2 34 4
Ann_3 11 5
and from that I am running this query:从那里我正在运行这个查询:
SELECT SUBSTRING_INDEX(subusers,'_',1) AS user,
SUM(COALESCE(Revenue,0)) AS charge
FROM emprevntb
WHERE Hour BETWEEN '3' AND '5'
AND SUBSTRING_INDEX(subusers,'_',1) IN
(SELECT Username FROM mainusertb WHERE STATUS='Active')
GROUP BY SUBSTRING_INDEX(subusers,'_',1);
from that I could able to get following result,从中我可以获得以下结果,
user charge
Ann 11
Mike 66
But I need to order them with asc order and all the users as well.但我需要用 asc 顺序和所有用户来订购它们。 Here what I need.这是我需要的。
user charge
Mike 66
Ann 11
Michel 0
John 0
Anonymous 0
Can someone show me where to change?有人可以告诉我在哪里改变吗?
Join from the user table to the other table containing the data, then aggregate by user:从用户表连接到包含数据的另一个表,然后按用户聚合:
SELECT
u.Username,
COALESCE(SUM(e.Revenue), 0) AS charge
FROM mainusertb u
LEFT JOIN emprevntb e
ON SUBSTRING_INDEX(e.subusers, '_', 1) = u.Username AND
e.Hour BETWEEN '3' and '5'
GROUP BY
u.Username;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.