Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/21.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
用于计算X/Y记录的SQL脚本_Sql_Sql Server - Fatal编程技术网

用于计算X/Y记录的SQL脚本

用于计算X/Y记录的SQL脚本,sql,sql-server,Sql,Sql Server,我正在尝试使用X/Y计数为我的记录编制索引,但有一些问题。以下是一个例子: 表 BOL# PalletID Shipper ColX ColY 12 3600 FDX 12 3601 FDX 12 3602 FDX 12 3603 FDX 13 3604 FDX 13 3605 FDX 13 3606 FDX 我需要一个脚本,将填充ColX和ColY。ColX应该是按

我正在尝试使用X/Y计数为我的记录编制索引,但有一些问题。以下是一个例子:

BOL#  PalletID  Shipper  ColX   ColY   
12    3600      FDX
12    3601      FDX
12    3602      FDX
12    3603      FDX
13    3604      FDX
13    3605      FDX
13    3606      FDX
我需要一个脚本,将填充ColX和ColY。ColX应该是按BOL#顺序计数和中断的。ColY也应该是BOL的ColX break的最大值

结果应如下所示:

BOL#  PalletID  Shipper  ColX  ColY   
12    3600      FDX       1     4
12    3601      FDX       2     4
12    3602      FDX       3     4
12    3603      FDX       4     4
13    3604      FDX       1     3
13    3605      FDX       2     3
13    3606      FDX       3     3

谢谢你的帮助。谢谢

您正在寻找窗口功能。对于您提供的示例:

select t.*,
       row_number() over (partition by bol order by palletid) as colx,
       count(*) over (partition by bol) as coly
from tablea t;

您正在寻找窗口函数。对于您提供的示例:

select t.*,
       row_number() over (partition by bol order by palletid) as colx,
       count(*) over (partition by bol) as coly
from tablea t;

这里有另一种使用交叉应用的方法,但任何一天我都会选择Gordan的解决方案

select t.*,
       row_number() over (partition by bol order by palletid) as colx,
       cs.coly
from tablea t;
CROSS APPLY 
(SELECT COUNT(1) from tablea where a.bol = b.bol) cs (coly)
或者使用
相关子查询

select t.*,
       row_number() over (partition by bol order by palletid) as colx,
       (SELECT COUNT(1) from tablea where a.bol = b.bol) as coly
from tablea t;

这里有另一种使用交叉应用的方法,但任何一天我都会选择Gordan的解决方案

select t.*,
       row_number() over (partition by bol order by palletid) as colx,
       cs.coly
from tablea t;
CROSS APPLY 
(SELECT COUNT(1) from tablea where a.bol = b.bol) cs (coly)
或者使用
相关子查询

select t.*,
       row_number() over (partition by bol order by palletid) as colx,
       (SELECT COUNT(1) from tablea where a.bol = b.bol) as coly
from tablea t;

这是一个快速的转变。你抢先找到了解决方案,这是一个快速的转变。你比我先找到解决办法。