所以我有4个单独的MySQL查询用于获得评级:
-- Get average rating for this week, and a count of each rating
select my_user as Login, EXTRACT(WEEK from (update_date)) as 'WeekNo',
COUNT(CASE WHEN rating = 1 THEN 1 ELSE NULL END) AS '1-Stars',
COUNT(CASE WHEN rating = 2 THEN 1 ELSE NULL END) AS '2-Stars',
COUNT(CASE WHEN rating = 3 THEN 1 ELSE NULL END) AS '3-Stars',
COUNT(CASE WHEN rating = 4 THEN 1 ELSE NULL END) AS '4-Stars',
COUNT(CASE WHEN rating = 5 THEN 1 ELSE NULL END) AS '5-Stars',
round(avg(rating),2) as 'WeekAvg'
from rating_table where my_user IN ('u1','u2','u3')
AND EXTRACT(YEAR from (update_date)) = 2016
AND EXTRACT(WEEK from (update_date)) = (WEEKOFYEAR(NOW()) - 1)
GROUP BY 1 ORDER BY 1;
-- get the average rating for the past 90 days
SELECT my_user as 'Login', round(avg(rating),2) as '90-day'
FROM rating_table
WHERE update_date BETWEEN NOW() - INTERVAL 90 DAY AND NOW()
AND my_user in ('u1','u2','u3')
GROUP BY 1;
-- get the average rating for Year to date
SELECT my_user as 'Login', round(avg(rating),2) as 'YTD'
FROM rating_table
WHERE (update_date BETWEEN '2016-01-01 00:00:00' AND NOW())
AND my_user in ('u1','u2','u3')
GROUP BY 1;
-- get the average rating for the past 365 days
SELECT my_user as 'Login', round(avg(rating),2) as '365-day'
FROM rating_table
WHERE update_date BETWEEN NOW() - INTERVAL 365 DAY AND NOW()
AND my_user in ('u1','u2','u3')
GROUP BY 1;
我已经尝试了各种方法将这些方法放入单个查询/表格中,但我无法让这些工作正常。这就是我想要输出的方式:
+----------+--------+---------+---------+---------+---------+---------+---------+--------+------+---------+
| Agent | WeekNo | 1-Stars | 2-Stars | 3-Stars | 4-Stars | 5-Stars | WeekAvg | 90-day | YTD | 365-day |
+----------+--------+---------+---------+---------+---------+---------+---------+--------+------+---------+
| u1 | 26 | 0 | 0 | 0 | 0 | 6 | 5.00 | 5.00 | 5.00 | 5.00 |
| u2 | 26 | 0 | 0 | 0 | 1 | 9 | 4.90 | 4.90 | 4.90 | 4.90 |
| u3 | 26 | 0 | 0 | 0 | 0 | 1 | 5.00 | 5.00 | 5.00 | 5.00 |
+----------+--------+---------+---------+---------+---------+---------+---------+--------+------+---------+
我试过了:
这些查询是针对只读表运行的,因此我可以使用的方法受到限制。
我知道我接近答案,但它并没有点击我。有人能就此提出一些建议吗?
答案 0 :(得分:0)
你是否尝试过LEFT JOIN?
提示:
FROM rating_table rt
LEFT JOIN rating_table as rt90 ON rt.my_user = rt90.my_user ...
LEFT JOIN rating_table as rtY ON rt.my_user = rtY.my_user ...
LEFT JOIN rating_table as rt365 ON rt.my_user = rt365.my_user ...
答案 1 :(得分:0)
您可以简单地将它们作为不同的子查询加入:
Select * from
(Select * from ... /*your 1st query*/ ) t1
Join (Select * from ... /*your 2nd query*/ ) t2
on t1.Login=t2.login
Join (Select * from ... /*your 3rd query*/ ) t3
on t1.Login=t3.login
Join (Select * from ... /*your 4th query*/ ) t4
on t1.Login=t4.login