2017-09-25 33 views
-1

我有一些表存儲金額,我想分組並得到總和 - 多表的原因是nhibernate descriminators。 我使用聯盟所有和工作,但查詢是非常大的。從不同的表求和Sql服務器

我使用下面的查詢

 SELECT CustomerAccountNumber, 
     vc.CustomerName, 
     SUM(PermAmount) AS PermAmount, 
     SUM(FreetextAmount) AS FreetextAmount, 
     (SUM(PermAmount) + SUM(FreetextAmount)) AS TotalAmountByCustomer 
FROM 
(
    SELECT pp.CustomerAccountNumber, 
      pl.Amount AS PermAmount, 
      0 AS FreetextAmount 
    FROM dbo.PermanentPlacementTransactionLine pl 
     INNER JOIN dbo.TransactionLine tl ON pl.TransactionLineId = tl.Id 
     INNER JOIN dbo.PermanentPlacement pp ON pl.PermanentPlacementId = pp.Id 
    WHERE tl.CurrentStatus = 1 
    GROUP BY pp.CustomerAccountNumber, 
      pl.Amount, 
      tl.Id 
    UNION ALL 
    SELECT ft.CustomerAccountNumber, 
      0 AS PermAmount, 
      ft.Amount AS FreetextAmount 
    FROM dbo.FreeTextTransactionLine fttl 
     INNER JOIN dbo.TransactionLine tl ON fttl.TransactionLineId = tl.Id 
     INNER JOIN dbo.[FreeText] ft ON fttl.FreeTextId = ft.Id 
    WHERE tl.CurrentStatus = 1 
    GROUP BY ft.CustomerAccountNumber, 
      ft.Amount, 
      tl.Id 
) WIPSummary 
INNER JOIN dbo.vw_Customer vc ON WIPSummary.CustomerAccountNumber = vc.CustomerAccount 
GROUP BY CustomerAccountNumber, 
     vc.CustomerName; 

有單獨的列中顯示量的任何優雅的方式? 我可以使用分區,如果它是相同的表,並希望逐行顯示。

+0

你可以顯示這個查詢的小樣本輸出和你想要的輸出嗎?如果你首先在CTE中包裝它,你可以使用一個分區。 – Simon

回答

1

試試這些查詢,很容易理解,可能比您的還要快。

我假設值是唯一在你看來

WITH cte_a 
    AS (SELECT pp.customeraccountnumber 
       ,Sum(pl.amount) AS PermAmount 
       ,0    AS FreetextAmount 
     FROM dbo.permanentplacementtransactionline pl 
       INNER JOIN dbo.transactionline tl 
         ON pl.transactionlineid = tl.id 
       INNER JOIN dbo.permanentplacement pp 
         ON pl.permanentplacementid = pp.id 
     WHERE tl.currentstatus = 1 
     GROUP BY pp.customeraccountnumber), 
    cte_b 
    AS (SELECT ft.customeraccountnumber 
       ,0    AS PermAmount 
       ,Sum(ft.amount) AS FreetextAmount 
     FROM dbo.freetexttransactionline fttl 
       INNER JOIN dbo.transactionline tl 
         ON fttl.transactionlineid = tl.id 
       INNER JOIN dbo.[freetext] ft 
         ON fttl.freetextid = ft.id 
     WHERE tl.currentstatus = 1 
     GROUP BY ft.customeraccountnumber) 
SELECT vc.customeraccountnumber 
     ,vc.customername 
     ,Isnull(A.permamount, 0)  AS PermAmount 
     ,Isnull(B.freetextamount, 0) AS FreetextAmount 
     ,Isnull(A.permamount, 0) 
     + Isnull(B.freetextamount, 0) AS TotalAmountByCustomer 
FROM dbo.vw_customer vc 
     LEFT JOIN cte_a a 
       ON vc.customeraccount = A.customeraccountnumber 
     LEFT JOIN cte_b b 
       ON vc.customeraccount = A.customeraccountnumber 

如果沒有表結構和樣本數據,這是我可以做些什麼來幫助你是最好的。