优化重复联盟所有SSMS查询

时间:2017-11-19 19:45:43

标签: sql sql-server ssms union-all ssms-2016

我正在创建一个将上传到QuickBooks的报告。由于每个查询中的单个计算更改,我必须进行UNION ALL 7查询。以下是前两个查询的示例:

SELECT
    Clients.Id
    ,@CNumber as 'Check Number'
    ,@TDate as 'Transac Date'
    ,CONCAT(@Memo, 'Debt') as 'Memo'
    ,Compensation.Payment as 'Amount'

FROM Compensation

    JOIN Clients on Id = Compensation.ClientId

UNION ALL

SELECT
    Clients.Id
    ,@CNumber as 'Check Number'
    ,@TDate as 'Transac Date'
    ,CONCAT(@Memo, 'Insurance') as 'Memo'
    ,InsuranceInvoices.WeeklyAmount

FROM InsuranceInvoices

有没有办法消除为每个联盟重复Clients.Id,@ CNC,@ TWate,CONCAT(@Memo,Variable)的需要?

对于CONCAT(@MEMO,变量)作为'Memo',我可以在Union ALL的每个新迭代中创建一个数组并插入(不知道是否可能)。

我遇到的问题是,不确定如何创建一个迭代前4列的循环,每次计算'Amount'。

这仅用于优化/代码可读性的目的。查询有效,并不是那么慢。然而,它长达155行,我想知道下次我做类似的事情时,我可以尝试这样做。

到目前为止我研究的内容:以下Stack Overflow link有点类似,但是,它没有使用不同的'FROM'表。数据来自单个表格。我的数据来自4个表格。下面是来自同一个表的两个查询的示例:

    SELECT
        Clients.Id
        ,@CNumber as 'Check Number'
        ,@TDate as 'Transac Date'
        ,CONCAT(@Memo, 'Debt') as 'Memo'
        ,Compensation.PaybackAmount as 'Amount'

    FROM Compensation

        JOIN Clients on Id = Compensation.ClientId

    WHERE
        Compensation.Week = @TrailingWeekEnd

UNION ALL

    SELECT
        Clients.Id
        ,@CNumber as 'Check Number'
        ,@TDate as 'Transac Date'
        ,CONCAT(@Memo, 'Vehicle') as 'Memo'
        ,Compensation.VDAccumulation as 'Amount'

    FROM ContractorSettlements

        JOIN Clients on Id = Compensation.ClientId

    WHERE
        Compensation.Week = @TrailingWeekEnd

如果这是一个糟糕的问题,我很抱歉。在我看来,我想这会在一个循环中工作,但老实说我不知道​​如何优化它。如果我能提供更多信息,请告诉我。

1 个答案:

答案 0 :(得分:1)

尽管您在查询中使用了错误的语法,但您可以使用以下

<强>解释

  1. 仅查询从表中提取所需的数据
  2. 通过为每个表添加类型来区分数据,例如DebtVehicle
  3. 将结果与您想要的参数相结合
  4. 查询

    ;with report as(
        select [Id] = ClientId,
               [Amount] = PaybackAmount,
               [Type] = 'Debt'
        Compensation c 
        where c.Week = @TrailingWeekEnd
        union all
        select ClientId,
               VDAccumulation,
               'Vehicle'
        from ContractorSettlements c
        where c.Week = @TrailingWeekEnd
    )
    select Id,
           [Check Number] = @CNumber,
           [Transac Date] = @TDate,
           [Memo] = Concat(@Memo,[Type]),
           Amount
    from report
    

    希望这会对你有所帮助