2017-07-12 94 views
-1

嗨我想獲得作爲一個記錄每個不同AgreeId的金額的總和,並且它應該包含該結果的所有其他列作爲一個記錄好。這是我的SP。請幫助我。選擇具有相同Id的列作爲一個記錄以及其他列

ALTER PROCEDURE sp_Contracts 
@ClientId INT 
,@LocationId INT = NULL 
,@UserId INT = NULL 
AS 
BEGIN 
SET NOCOUNT ON; 

IF (@LocationId = 0) 
BEGIN 
    SET @LocationId = NULL 
END 

SELECT 

    a.AgreementNumber 
    ,a.RONo 
    ,a.PONo 
    ,round([dbo].func_GetAgreementTotalNew (a.AgreementId),2) as 'Total' 
    ,round(a.Discount,2) as 'AdjustmentPostTax' 
    ,round(p.Amount,2) as 'AmountPaid' 
    ,p.PaymentMethod 

FROM tblPay AS p 

INNER JOIN tblAgree AS a ON p.AgreeId = a.AgreeId 
WHERE 
    a.ClientId = @ClientId 
    AND a.[Status] <> 6 
    AND (
     (
      @LocationId IS NULL 
      AND (
       A.CheckoutLocation IN (
        SELECT LocationId 
        FROM [dbo].[tblUserLocations] 
        WHERE UserID = @userId 
         AND IsDeleted = 0 
        ) 
       OR A.CheckoutLocation IS NULL 
       ) 
      ) 
     OR A.CheckoutLocation = @LocationId 
     ) 
    END 
+0

您使用的是MySQL還是MS SQL Server?不要標記不涉及的產品。 – jarlh

+0

此外,表設計將幫助在到達查詢 – ArunGeorge

+0

首先修復您的標記,這看起來像SQL服務器,所以刪除mysql標記。其次,[不要用'sp_'](https://msdn.microsoft.com/en-us/library/dd172115(v = vs.100).aspx)前綴存儲的特效。第三,提供一些樣本數據和期望的輸出。 – Tanner

回答

0

如果您使用MSSQL,則可以使用窗口分析函數計算聚合值,而不使用GROUP BY子句。

SELECT 
    a.AgreementNumber 
    ,a.RONo 
    ,a.PONo 
    ,round([dbo].func_GetAgreementTotalNew (a.AgreementId),2) as 'Total' 
    ,round(a.Discount,2) as 'AdjustmentPostTax' 
    ,round(p.Amount,2) as 'AmountPaid' 
    ,p.PaymentMethod 
    , SUM(p.Amount) OVER (PARTITION BY p.AgreeId) AS TOT_FOR_ID 
FROM tblPay AS p 
INNER JOIN tblAgree AS a ON p.AgreeId = a.AgreeId 
WHERE a.ClientId = @ClientId 
     AND a.[Status] <> 6 
... 
相關問題