SQL存储过程使用子查询中的主查询结果

时间:2017-02-06 08:01:18

标签: sql-server crystal-reports

我为Crystal Reports制作了一个存储过程。它还没有工作,我还没有想到如何解决这个问题。这是我的问题:

use [fmsAir];
WITH Main AS (
    SELECT  [File].[FileNumber], [CostRevenue].[COSTAMOUNT], [CostRevenue].[RevenueAmount], [File].[FileDate], [CostRevenue].[REVENUERATE], [CostRevenue].[CostRate], [CostRevenue].[REVENUECURRENCY],
            [File].[COMPANY], [CostRevenue].[CRNUMBER], [CostRevenue].[IINVOICENUMBER], [File].[RELATIONCODE], [CostRevenue].[COSTRELATIONCODE], [CostRevenue].[REVENUEDESCRIPTION]
    FROM    
            [fmsAir].[dbo].[File]
    INNER JOIN
            [fmsAir].[dbo].[CostRevenue] ON [File].[FILENUMBER] = [CostRevenue].FILENUMBER
    WHERE
            [File].[FILEDATE] BETWEEN '2016-08-01 00:00:00' AND '2018-01-20 00:00:00' AND
            [File].[FILENUMBER] > 500
),
Relation AS (
    SELECT [Relation].[Companyname], [Relation].[RELATIONCODE]
    FROM [fms].[dbo].[Relation]
    WHERE [Relation].[Relationcode] = Main.[File].[RELATIONCODE]
),
OutgoingInvoiceLine AS (
    SELECT [OutgoingInvoiceLine].[AMOUNT], [OutgoingInvoiceLine].[RATE], [OutgoingInvoiceLine].[Currency], [OutgoingInvoiceLine].[CRNUMBER]
    FROM [fmsAir].[dbo].[OutgoingInvoiceLine]
    WHERE [OutgoingInvoiceLine].[CRNUMBER] = Main.[CostRevenue].[CRNUMBER]
),
IncomingInvoiceLine AS (
    SELECT [IncomingInvoiceLine].[AMOUNT], [IncomingInvoiceLine].[RATE], [IncomingInvoiceLine].[CURRENCY], [IncomingInvoiceLine].[CRNUMBER]
    FROM [fmsAir].[dbo].[IncomingInvoiceLine]
    WHERE [IncomingInvoiceLine].[CRNUMBER] = Main.[CostRevenue].[CRNUMBER]
),
RelationCost AS (
    SELECT [Relation].[CompanyNAME], [Relation].[RelationCode]
    FROM [fms].[dbo].[Relation]
    WHERE Relation.RELATIONCODE = Main.[CostRevenue].[COSTRELATIONCODE]
)
SELECT main.FILENUMBER, main.COSTAMOUNT from Main 

现在我使用WHERE然后使用Main。的部分不起作用,因为这不是你可以使用它的方式,但我不知道怎么做的方法正确的方式。有人可以帮我做这个工作吗?

这些是错误:

  

Msg 4104,Level 16,State 1,Line 16   无法绑定多部分标识符“Main.File.RELATIONCODE”。   消息4104,级别16,状态1,行21多部分标识符   无法绑定“Main.CostRevenue.CRNUMBER”。消息4104,级别16,   状态1,第26行多部分标识符“Main.CostRevenue.CRNUMBER”   无法受约束。 Msg 4104,Level 16,State 1,Line 31 The   多部分标识符“Main.CostRevenue.COSTRELATIONCODE”不可能   界。

提前谢谢!

2 个答案:

答案 0 :(得分:0)

尝试在cte表达式中创建列名,并在下面提到的cte中使用该列名。 我希望这会有所帮助

答案 1 :(得分:0)

如果你只从第一个cte表中获取结果,为什么你使用4 cte。