创建在SQL中返回表的函数

创建在SQL中返回表的函数,sql,sql-server,stored-procedures,view,table-functions,Sql,Sql Server,Stored Procedures,View,Table Functions,我想用一些逻辑来创建视图,比如使用(for循环,if..else),但因为SQL不支持这种逻辑 我想创建一个不带参数并返回表的表函数 我有一张关于订单的表格,如下所示 OrderId Destination Category Customer ---------------------------------------- 6001 UK 5 Adam 6002 GER 3 Jack ID Order

我想用一些逻辑来创建视图,比如使用(for循环,if..else),但因为SQL不支持这种逻辑 我想创建一个不带参数并返回表的表函数

我有一张关于
订单的表格,如下所示

OrderId  Destination  Category  Customer
----------------------------------------
6001     UK           5         Adam
6002     GER          3         Jack
ID  OrderID  TrackingID
-----------------------
1   6001     1
2   6001     2
3   6002     2
跟踪订单的表格如下

OrderId  Destination  Category  Customer
----------------------------------------
6001     UK           5         Adam
6002     GER          3         Jack
ID  OrderID  TrackingID
-----------------------
1   6001     1
2   6001     2
3   6002     2
下面是跟踪的
类型

ID  Name
--------------
1   Processing
2   Shipped
3   Delivered
正如您在跟踪订单
中所看到的,订单号可能有多条记录,具体取决于发生的跟踪事件的数量

我们有超过25种跟踪类型,我在这里没有包括。这意味着一个订单可以在
跟踪订单
表中存在25次

说到这里,我的要求是创建如下视图,条件是订单必须属于5或3个类别(我们有超过15个类别)

无论何时运行函数,它都必须返回更新的信息

因此,例如,当新跟踪发生并插入到
跟踪顺序中时,我希望运行我的函数并在相应的标志列中查看更新(例如
isDelivered


我对实现这一目标的最佳方式感到困惑。我不需要确切的脚本,我只需要理解实现它的方法,因为我对SQL不是很熟悉,它可以通过使用条件聚合的交叉表查询来完成。像这样的

select o.OrderID, 
       max(case when tt.[Name]='Processing' then 1 else 0 end) isPrepared,
       max(case when tt.[Name]='Shipped' then 1 else 0 end) isShipped,
       max(case when tt.[Name]='Delivered' then 1 else 0 end) isDelivered
from orders o
     join tracking_orders tro on o.OrderID=tro.OrderID
     join tracking_types tt on tro.TrackingID=tt.TrackingID
where o.category in(3, 5)
group by o.OrderID;
[编辑]要分解第3类订单,在交叉选项卡中添加了3个附加列

select o.OrderID, 
       max(case when tt.[Name]='Processing' then 1 else 0 end) isPrepared,
       max(case when tt.[Name]='Shipped' then 1 else 0 end) isShipped,
       max(case when tt.[Name]='Delivered' then 1 else 0 end) isDelivered,
       max(case when tt.[Name]='Processing' and o.category=3 then 1 else 0 end) isC3Prepared,
       max(case when tt.[Name]='Shipped' and o.category=3 then 1 else 0 end) isC3Shipped,
       max(case when tt.[Name]='Delivered'  and o.category=3 then 1 else 0 end) isC3Delivered
from orders o
     join tracking_orders tro on o.OrderID=tro.OrderID
     join tracking_types tt on tro.TrackingID=tt.TrackingID
where o.category in(3, 5)
group by o.OrderID;

我不明白你为什么不能在查询中这样做。您可以使用
PIVOT
来example@Wouter谢谢你的回答,我们想把它作为视图,这样我们就可以直接从我们的API调用它了。不过,我会调查一下,我同意沃特的评论。如果您最终选择了函数路径:您希望创建一个所谓的“表值函数”(返回一个表)。见文件的第1部分。示例B和C显示了表值函数。@rav这就是我的意思,创建一个查询并将其放入view@Wouter就我从阅读中了解的情况而言,我们不能在视图中使用If-else语句。此外,我不希望所有的订单都被退回,我只希望5和3类。此外,在类别5的情况下,如果出现某种跟踪类型,我希望订单记录出现在我的视图中。例如,如果是类别5,跟踪类型为类型2,则应包括记录和许多类似的条件。如果发生跟踪类型2,我只想检索属于类别3的订单,该怎么办?列“orders.OrderID”在选择列表中无效,因为它不包含在聚合函数中或者是GROUP BY条款。更新为GROUP BY谢谢你的快速回复,我真的很感激。但我想你误解了我的意思。我想检索类别3和类别5的订单,但在类别3的情况下,我只想检索具有跟踪类型2的订单,它为类别3的订单划分了订单类型指示器