首页 > 解决方案 > 我有一个 WITH 子句不会按预期运行

问题描述

我发现了这个 WITH 子句,我根据我的目的进行了修改。我不能说我完全理解当我在它自己内部裁判它时它是如何工作的?

正如您从图片中看到的那样,我在最后几行“4 gjutning”和“5 Målning”上得到了重复。

在此处输入图像描述

所以基本上有一个用于不同面板的关系表,您应该能够在其中设置工作流程。一个面板紧随其后,在这种情况下,我也有平行面板。“3 Montering A”和“3 Montering B”是从 RunOrder 中可以看到的平行面板,然后它们合并为“4 Gjutning”,然后是“5 Målning”

WITH PanelStructure as
(
  Select  p.factoryId, p.name Panel, p.HasScreen, ppr.ParentPanelId, ppr.PanelId, CAST(ppr.PanelId AS VarChar(Max)) as Level, CAST(1 AS int) RunOrder from PanelProductRelation ppr
inner JOIN  Panel p on ppr.PanelId=p.id
where ppr.productid=1 and ParentPanelId=0 and p.CustomerId=7 --and p.HasScreen=1
  UNION ALL
  Select  p2.factoryId, p2.name Panel,p2.HasScreen, ppr2.ParentPanelId, ppr2.PanelId,CAST(ppr2.PanelId AS VarChar(Max)) + ', ' + M.Level, CAST(1 AS int) + M.RunOrder
    from PanelProductRelation ppr2
    Inner JOIN  Panel p2 on ppr2.PanelId=p2.id
     INNER JOIN PanelStructure M ON m.PanelId = ppr2.ParentPanelId
    where ppr2.productid=1 and p2.CustomerId=7 and p2.HasScreen=1
 )
SELECT ps.* From PanelStructure  ps
LEFT JOIN (Select ps2.ParentPanelId ParentPanelId ,count(ParentPanelId) ParentPanelIdCount from PanelStructure ps2 group by ps2.ParentPanelId  ) dup ON dup.ParentPanelId=ps.ParentPanelId
;

标签: sqlsql-servertsqlcommon-table-expression

解决方案


你有没有想过distinct在你的select陈述中加入?因此,您的结果中不会出现双行。


推荐阅读