Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
按组的SQL求和_Sql - Fatal编程技术网

按组的SQL求和

按组的SQL求和,sql,Sql,我有下表:- 表 我希望将上述内容转化为:- 条件:- 它始终基于最新的交易。例如,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'

我有下表:-

我希望将上述内容转化为:-

条件:- 它始终基于最新的交易。例如,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
然而,我得出的结果如下:-


谢谢。

我想您不想在分组中包括长度和数量。你的意思是按范围和等级分组吗?是的,按范围和等级分组。一个小提琴链接会很有用。我对Stack Exchange很陌生,把它作为一个答案贴出来是不是很有礼貌?如果它的
sql server
尝试在
CTE
的帮助下按范围进行分区,那么你会按CTE.Range对(CTE.qty)组进行求和吗?