Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/71.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 Server窗口函数_Sql_Sql Server_Azure Sql Database - Fatal编程技术网

用于日期差异的SQL Server窗口函数

用于日期差异的SQL Server窗口函数,sql,sql-server,azure-sql-database,Sql,Sql Server,Azure Sql Database,假设我有这个表: // Orders OrderId Customer OrderDate ------------------------------ 1 Jack 2018/05/01 2 Jack 2018/05/05 3 Jack 2018/05/15 4 Jack 2018/05/18 5 Jack 2018/05/21 6

假设我有这个表:

// Orders

OrderId    Customer  OrderDate      
------------------------------
1          Jack      2018/05/01
2          Jack      2018/05/05
3          Jack      2018/05/15
4          Jack      2018/05/18
5          Jack      2018/05/21
6          Alex      2018/06/11
7          Alex      2018/06/12
8          Alex      2018/06/17
9          Alex      2018/06/18
我想用一个查询在一列中显示他们订单之间的间隔天数,如下所示:

Customer    Gaps             GapAverage
---------------------------------------
Jack        4, 10, 3, 3      5
Alex        1, 5, 3          3
因此,对于杰克来说,他的第二份订单是在第一份订单之后4天,第三份订单是在第二份订单之后10天,并且。。。 他的平均间隔是5天

如何在SQL server中编写查询以获得这样的结果?

我得到了这样的查询

select q1.Customer, 
       STRING_AGG(q1.diff, ',') as Gaps, 
       AVG(diff) as GapAverage
from ( select Customer as Customer, 
       DATEDIFF(dd, [OrderDate], LEAD([OrderDate]) OVER (PARTITION  BY Customer ORDER  BY Customer)) as diff
       from OrderT) as q1
group by q1.Customer

我正在使用一个函数访问当前行后面的行。使用此函数的OVER参数,我将结果按Customer字段划分为多个组。使用该函数,我可以在几天内获得间隙。

您认为这与窗口函数有什么关系?您可以在google上搜索“sql server字符串聚合”。@GordonLinoff,因为我希望对它们进行分组,每个组都应该进行排序,每个值都应该基于其上一行进行计算。仅使用字符串聚合怎么可能做到这一点。SQL Server 2017中的函数是
string_agg()
:.@GordonLinoff如何聚合
thisRow.OrderDate-previousRow.OrderDate
?@mehrandvd如果您需要将string_agg替换为其他替代函数,请告诉我。在这种情况下,我将编辑我的答案。请注意,字符串_AGG仅在MSSQL 2017及更高版本中可用。如果你不使用MSSQL 2017,你需要做一些棘手的事情。
STRING\u AGG
在Azure中很好