一年的SQL总计,也设置了一段时间

时间:2016-04-23 11:40:41

标签: mysql sql join sum

我有以下SQL数据库:tablename

date        fname   surname     points  display
2015-08-08  John    Lennon      5       1
2015-08-16  Ringo   Starr       2       1
2015-08-24  Paul    McCartney   3       1
2015-10-07  George  Harrison    1       1
2015-10-15  John    Lennon      3       1
2015-10-23  Ringo   Starr       5       1
2015-12-07  George  Harrison    1       1
2015-12-14  Ringo   Starr       5       1
2015-12-22  George  Harrison    3       1
2016-02-03  Paul    McCartney   4       1
2016-02-13  John    Lennon      5       1
2016-02-20  Paul    McCartney   1       1
2016-04-04  Ringo   Starr       2       1
2016-04-09  George  Harrison    2       1
2016-04-20  John    Lennon      5       1

目前我只使用此数据库来提取当前年份的显示='1'的总分,并使用以下代码:

SELECT id, fname, surname, points, CONCAT(surname,forename) 'fullname', SUM(points) AS total_points
FROM tablename 
WHERE date >= '2016-01-01' AND display ='1' 
GROUP BY fname, surname
ORDER BY total_points DESC, surname ASC, forename ASC

但是我想在结果中添加一些额外的数据,给我过去15天的积分。我可以通过使用:

来自行解决这个问题
SELECT id, fname, surname, points, CONCAT(surname,forename) 'fullname', SUM(points) AS fifteenday_points
FROM tablename 
WHERE date >= '2016-04-08' AND display ='1' 
GROUP BY fname, surname
ORDER BY total_points DESC, surname ASC, forename ASC

那么,我该怎么做呢?我需要使用某种加入方式吗?如果是这样,由于不同的WHERE语句,我甚至在哪里开始?或者我可以对第一个查询进行简单的添加,这将允许我返回fifteenday_points数据?

2 个答案:

答案 0 :(得分:1)

您可以通过以下方式加入他们:

SELECT fname, surname, CONCAT(surname,fname) AS fullname,  SUM(points) AS total_points, fifteenday_points
FROM tablename JOIN (
    SELECT CONCAT(surname,forename) 'fullname', SUM(points) AS fifteenday_points
    FROM tablename 
    WHERE date >= NOW() - INTERVAL 15 DAY  AND display ='1' 
    GROUP BY fullname) AS fifteen_days
    ON tablename.fullname = fifteen_days.fullname
WHERE YEAR(date) = YEAR(NOW()) AND display ='1' 
GROUP BY fullname
ORDER BY total_points DESC, fullname ASC

我也改变了数据的条件

答案 1 :(得分:0)

SELECT tablename.fname, tablename.surname, CONCAT(tablename.surname,tablename.fname) AS 'fullname',  SUM(points) AS total_points, fifteenday_points
FROM tablename JOIN (
SELECT tablename.fname, tablename.surname, SUM(points) AS fifteenday_points
FROM tablename 
WHERE enddate >= NOW() - INTERVAL 15 DAY  AND display ='1' 
GROUP BY tablename.surname, tablename.fname) AS fifteen_days
ON tablename.surname = fifteen_days.surname AND tablename.fname = fifteen_days.fname
WHERE YEAR(enddate) = YEAR(NOW()) AND display ='1' 
GROUP BY tablename.surname, tablename.fname
ORDER BY total_points DESC, tablename.surname ASC, tablename.fname ASC;

感谢Vitto和Reto让我走上了正确的道路。