检索同一查询中的总点数和每周总计

时间:2012-09-26 10:57:00

标签: mysql

我正在尝试查询我的奖励数据库,以确定工作人员已分配总计本周的点数。

我用来计算教师分配的点的查询如下:

SELECT  `Giver_ID` , SUM(  `Points` ) AS TotalPoints
FROM  `transactions` 
GROUP BY  `Giver_ID` 
ORDER BY  `Giver_ID` ASC 

我用来计算每周分配的查询非常相似:

SELECT  `Giver_ID` , SUM(  `Points` ) AS WeeklyPoints
FROM  `transactions`
WHERE ( `Datetime` >= '2012-09-24' AND `Datetime` <= '2012-09-30' )
GROUP BY  `Giver_ID` 
ORDER BY  `Giver_ID` ASC 

我的问题是:是否可以将查询组合起来从单个查询中生成Giver_IDTotalPointsWeeklyPoints

提前致谢,

3 个答案:

答案 0 :(得分:2)

试试这个:

SELECT  a.`Giver_ID` , 
            MAX(b.`TotalPoints`) as `TotalPoints`, 
            MAX(c.`WeeklyPoints`) as `WeeklyPoints`
    FROM  `transactions` as a 
        LEFT JOIN (SELECT `Giver_ID`, SUM(`Points`) AS TotalPoints FROM `transactions` GROUP BY `Giver_ID`) as b ON a.`Giver_ID`=b.`Giver_ID`
        LEFT JOIN (SELECT `Giver_ID`, SUM(`Points`) AS WeeklyPoints FROM `transactions` WHERE ( `Datetime` >= '2012-09-24 00:00:00' AND `Datetime` <= '2012-09-30' ) GROUP BY `Giver_ID`) as c ON a.`Giver_ID`=c.`Giver_ID`
    GROUP BY  a.`Giver_ID` 
    ORDER BY  a.`Giver_ID` ASC 

答案 1 :(得分:2)

是的,有可能 -

SELECT
  Giver_ID,
  SUM(Points) AS TotalPoints,
  SUM(IF(Datetime >= '2012-09-24' AND Datetime <= '2012-09-30', Points, NULL)) AS WeeklyPoints
FROM transactions
GROUP BY Giver_ID

答案 2 :(得分:0)

SELECT  `Giver_ID` , SUM( `Points`) AS WeeklyPoints,(SELECT SUM(`Points`)
FROM  `transactions` where `Giver_ID`=t.`Giver_ID` GROUP BY  `Giver_ID`)  AS TotalPoints
FROM  `transactions` t
WHERE ( `Datetime` >= '2012-09-24' AND `Datetime` <= '2012-09-30' )
GROUP BY  `Giver_ID` 
ORDER BY  `Giver_ID` ASC