SQL视图 - 嵌套SELECT?

时间:2014-07-25 22:12:44

标签: sql sql-server view

我正在尝试从下表创建一个视图。我正在寻找输出为CUSTOMER,最近或MAX(CALENDARDT)的CUSTOMER和SUM(QTY)字段,用于所有与MAX(CALENDARDT)记录具有相同CCYYMM字段的记录。

预期结果将是

1500627 03/25/2013 5 

5是CCYYMM字段中201303的最后两个记录的数量字段的总和

Customer  |CCYYMM   |CalendarDt|DocNumb|Qty
1500627 |201202 |02/01/2012|Z201202|0
1500627 |201203 |03/02/2012|2542484|7
1500627 |201205 |05/04/2012|2979222|3
1500627 |201206 |06/20/2012|3262548|2
1500627 |201207 |07/31/2012|3500794|1
1500627 |201208 |08/30/2012|6946730|1
1500627 |201209 |09/13/2012|3774092|1
1500627 |201210 |10/31/2012|4063932|3
1500627 |201211 |11/16/2012|Z201211|0
1500627 |201301 |01/04/2013|Z201301|0
1500627 |201301 |01/30/2013|Z201301|0
1500627 |201303 |03/01/2013|4876779|1
1500627 |201303 |03/25/2013|5044331|4

2 个答案:

答案 0 :(得分:0)

这对你有用。内部SELECT用于获取每个客户的最大日期,并且JOIN返回到原始表:

SELECT MyTable.Customer, 
       MaxDates.MaxDate,
       SUM(Qty) AS TotalQuantity
FROM MyTable
JOIN (SELECT Customer, 
             MAX(CalendarDT) AS MaxDate
      FROM MyTable
      GROUP BY Customer) AS MaxDates
    ON MaxDates.Customer = MyTable.Customer
    AND MaxDates.MaxDate = MyTable.CalendarDT
GROUP BY MyTable.Customer, MaxDates.MaxDate

答案 1 :(得分:0)

您可以明智地使用窗口函数来执行此操作:

select customer, calendardt, sumqty
from (select t.*,
             row_number() over (partition by customer order by calendardt desc) as seqnum,
             sum(qty) over (partition by ccyymm) as sumqty
      from followingtable t
     ) t
where seqnum = 1;

请注意,这假设短语:“SUM(QTY)字段,对于与MAX(CALENDARDT)记录具有相同CCYYMM字段的所有记录”适用于所有客户,而不仅仅是一个客户。如果要将其限制为一个客户,可以进行此修改:

select customer, calendardt, sumqty
from (select t.*,
             row_number() over (partition by customer order by calendardt desc) as seqnum,
             sum(qty) over (partition by customer, ccyymm) as sumqty
      from followingtable t
     ) t
where seqnum = 1;