请参阅以下SQL:
SELECT M.username, count(*) as Total, date(status_date) as Date FROM com_result
LEFT JOIN members as M on M.member_id = com_result.member_id
GROUP BY date(status_date), com_result.member_id Order By status_date DESC
这将显示基于DATE
和member_id
示例结果:
+----------+-------+------------+
| username | Total | DATE |
+----------+-------+------------+
| bx7 | 3 | 2012-09-10 |
| bx2 | 25 | 2012-09-04 |
| bx2 | 401 | 2012-09-03 |
| bx1 | 703 | 2012-09-02 |
| bx4 | 1075 | 2012-09-02 |
+----------+-------+------------+
它运行良好,现在我想合并/联合到另一个相同的表结构。 第二个SQL:
SELECT M.username, count(*) as Total, date(status_date) as Date FROM com_result_b
LEFT JOIN members as M on M.member_id = com_result_b.member_id
GROUP BY date(status_date), com_result_b.member_id Order By status_date DESC
假设com_result
的结果为:
| bx2 | 25 | 2012-09-04 |
com_result_b
的结果是:
| bx2 | 50 | 2012-09-04 |
所以当它合并/联合时 - 我希望结果如下:
| bx2 | 75 | 2012-09-04 |
正如您所看到的,Total
的值从两个表中的相同日期开始增加。怎么办?
答案 0 :(得分:2)
SELECT
username,
IF(q1.Total IS NULL,0,q1.Total)+IF(q2.Total IS NULL,0,q2.Total) AS Total,
q1.Date
FROM (
SELECT member_id, M.username, count(*) as Total, date(status_date) as Date
FROM com_result
LEFT JOIN members as M on M.member_id = com_result.member_id
GROUP BY date(status_date), com_result.member_id
) AS q1
LEFT JOIN (
SELECT member_id, M.username, count(*) as Total, date(status_date) as Date
FROM com_result_b
LEFT JOIN members as M on M.member_id = com_result_b.member_id
GROUP BY date(status_date), com_result_b.member_id
) AS q2 ON q1.member_id=q2.member_id AND q1.Date=q2.Date
ORDER BY q1.Date DESC
答案 1 :(得分:1)
使用SUM
select username,SUM(Total) , DATE
(
SELECT M.username, count(*) as Total, date(status_date) as Date FROM com_result_b
LEFT JOIN members as M on M.member_id = com_result.member_id
GROUP BY date(status_date), com_result.member_id
UNION ALL
SELECT M.username, count(*) as Total, date(status_date) as Date FROM com_result_b
LEFT JOIN members as M on M.member_id = com_result_b.member_id
GROUP BY date(status_date), com_result_b.member_id
) v
group by username, date
答案 2 :(得分:1)
SELECT X.username, SUM(X.Total) AS TOTAL , X.Date
FROM( SELECT ... FROM com_result Union Select .. From com_result_b)X
GROUP BY X.username, X.Date
答案 3 :(得分:0)
试试这个:
最简单的方法是:
您只需要将两个结果放在带有union all运算符的派生表中
SELECT username,SUM(Total),Date
FROM (
SELECT M.username, count(*) as Total, date(status_date) as Date
FROM com_result
LEFT JOIN members as M on M.member_id = com_result.member_id
GROUP BY date(status_date), com_result.member_id
union all
SELECT M.username, count(*) as Total, date(status_date) as Date
FROM com_result_b
LEFT JOIN members as M on M.member_id = com_result_b.member_id
GROUP BY date(status_date), com_result_b.member_id )a
GROUP BY username,Date
ORDER BY Date DESC