SQL自我加入MAX和Group By

时间:2014-03-20 20:00:49

标签: sql self-join

我有以下表格数据

ID      Amt EOP LID
==================================
1   10  3/31/2014   11

2   10  3/31/2014   12

3   5   3/31/2014   13

4   15  2/28/2014   11

5   10  2/28/2014   12

6   15  2/28/2014   13

7   5   1/31/2014   11

8   15  4/30/2014   12

9   10  4/30/2014   13

10  5   5/31/2014   11

11  20  5/31/2014   12

12  25  5/31/2014   13

我需要编写一个查询,当指定EOP = 5/31/2014时,将通过LID返回Sum(Amt)组 然后它将它与前一个月的总和(Amt)进行比较,即EID = 4/30/2014 group by LID并仅返回值不同的LID。

1 个答案:

答案 0 :(得分:0)

这样的事情会起到什么作用(SQL Server语法): 这个要求对我来说有点不清楚......

Select a.LID, a.currentmonth, b.lastmonth
from
    (select Sum(amt) as currentmonth, LID
     from MyTable
     where EOP = '2014-05-31'
     Group By LID ) a
left outer join 
    (select Sum(amt) as lastmonth, LID
     from MyTable
     where EOP = dateadd(month, -1, '2014-05-31')
     Group By LID) b on a.LID = b.LID

演示:http://sqlfiddle.com/#!3/09632/7