如何让下表仅显示具有最早日期的行以及新列中具有相同项目ID的“数量”总和。
如下图所示,
Name ItemID Date Qty
A A0001 25-Feb-14 23
B A0001 01-Apr-14 4
C A0001 18-Jul-14 54
D K0006 03-Mar-14 86
E K0006 11-Jan-14 29
F X0003 27-Sep-14 19
G X0003 12-Nov-14 28
这就是结果应该是什么样的,
Name ItemID Date Qty Total Outstanding
A A0001 25-Feb-14 23 81
E K0006 11-Jan-14 29 115
F X0003 27-Sep-14 19 47
答案 0 :(得分:2)
SELECT a.Name,a.ItemID,b.Date,a.Qty,b.Total FROM TableA a
INNER JOIN (SELECT ItemID,MIN(Date) AS Date,SUM(Qty)
AS Tatal FROM TableA GROUP BY ItemID)b ON
b.ItemID=a.ItemID AND a.Date=b.Date
答案 1 :(得分:1)
DECLARE @T TABLE (NAME VARCHAR(10),Itemid VARCHAR(10),da date,qty int)
insert into @T(NAME,Itemid,da,qty) values ('A','A0001','2014-02-25',23),
('B','A0001','2014-04-01',4),
('C','A0001','2014-07-18',54),
('D','K0006','2014-03-03',86),
('E','K0006','2014-01-11',29),
('F','X0003','2014-09-27',19),
('G','X0003','2014-11-11',28)
;with cte as (
select *,SUM(qty)OVER(PARTITION BY Itemid )total,
ROW_NUMBER()OVER(PARTITION BY Itemid ORDER BY da )RN from @T
group by NAME,Itemid,da,qty
)
select NAME,Itemid,convert(varchar,da,100)As [date],qty,total from cte
WHERE RN = 1
答案 2 :(得分:0)
试试这个:
with CTE
as(
select -- M.Name,
SUM(M.Qty) TotalOTD,M.ItemID,MIN(M.Date) as MDate from myTestTable M
GROUP BY M.ItemID )
select Name, D.ItemID, Date , Qty, TotalOTD from CTE
JOIN myTestTable D
ON CTE.ItemID=D.ItemID and CTE.MDate=D.date
输出
Name ItemID Date Qty TotalOTD
A A0001 2014-02-25 23 81
E K0006 2014-01-11 29 115
F X0003 2014-09-27 19 47
答案 3 :(得分:0)
Select Name, AliasID, DateAlias, Quantity, TotalOutstanding
from TableA A join
(Select ItemId as AliasID,Min(Date) as DateAlias,
Sum(Quantity) as TotalOutstanding
from TableA
group by ItemID )V
on A.ItemID=V.ItemID