2

我正在尝试查询我的奖励数据库,以了解员工本周总共分配了多少积分。

我用来计算老师分配的总分的查询如下

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从单个查询?

提前致谢,

4

3 回答 3

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 
于 2012-09-26T11:14:45.317 回答
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
于 2012-09-26T11:19:50.557 回答
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 
于 2012-09-26T10:59:59.383 回答