MySql:复杂聚合查询

时间:2014-10-21 21:36:34

标签: mysql

我的数据显示如下:

table: School_Work

ID  Pay_Date    Hours   Amount
1   1/5/2014    5       20
1   1/5/2014    7       30
1   1/5/2014    10      25
1   1/8/2014    15      30
1   1/9/2014    18      25
2   1/7/2014    5       15
2   1/7/2014    5       10
2   1/9/2014    7       15
2   1/9/2014    9       26
2   1/9/2014    10      100

我有以下查询atm:

SELECT ID, min(Pay_Date) as Start_Date, max(Pay_Date) as End_Date, sum(Amount) As Total_Without_Beginning_Start_Date
FROM School_Work
GROUP BY ID

代码工作正常,但我需要它不包括Start_Date计算总金额。

ID 1应该只是

30+25

ID 2应该只是

15+26+100

我也尝试过使用having子句但是没有用。谢谢你的输入〜

我需要结果

ID   Start_Date    End_Date   Total_Without_Beginning_Start_Date
1    1/5/2014      1/9/2014   55
2    1/7/2014      1/9/2014   141

1 个答案:

答案 0 :(得分:2)

您可以使用子查询来完成此操作(通常是一个坏主意,但对于轻量级或一次性查询它很好)。试试这个......

SELECT x.ID, 
       min(x.Pay_Date) as Start_Date, 
       max(x.Pay_Date) as End_Date, 
       sum(x.Amount) - (select sum(y.Amount) from School_Work y where y.ID = x.ID and y.Pay_Date = min(x.Pay_Date) order by y.Pay_Date asc limit 1) As Total_Without_Beginning_Start_Date
FROM School_Work x
GROUP BY x.ID