按组进行SQL求和

时间:2014-01-20 03:57:16

标签: sql

我有下表: -

表A

enter image description here

我希望将上述内容翻译成: -

enter image description here

条件: - 它始终基于最新的交易。例如,U001被记录两次 - 20140102123458& 20140103082526.在这种情况下,我们选择最新的20140103082526。

我使用以下SQL运行: -

select
CASE x.Length
when '20' then '20/22'
when '21' then '20/22'
when '22' then '20/22'
when '23' then '23/24'
when '24' then '23/24'
end as Range,
x.Grade, sum(x.Length) Length, sum(x.Qty) Qty
from TableA as x
inner join
(
select Serial, max(Transaction) Transaction
from TableA
group by Serial
) as y on (y.Transaction =x.Transaction)
where
x.Serial in ( ‘U001’,‘U002’,‘U003’,‘U004’,‘U005’)
group by x.Length, x.Grade, x.Qty

然而,我所得到的结果如下: -

enter image description here

感谢。

0 个答案:

没有答案