2013-06-18 87 views
0

我一直在試圖苗條此查詢下來,讓我得到的每個供應商ID和匯一排我SQL服務器:結合行

-- Insert statements for procedure here 
SELECT DISTINCT 
mast.VENDOR AS VendorID, 
mast.VENDOR_VNAME AS VendorName, 
addr.LOCATION_CODE AS 'Remit ID', 
mast.TAX_ID AS TIN, 
addr.ADDR1 AS Address1, 
addr.ADDR2 AS Address2, 
addr.CITY_ADDR5 AS City, 
addr.STATE_PROV AS St, 
addr.COUNTRY AS Country, 
addr.POSTAL_CODE AS Zip, 
count(inv.TRAN_TOT_TXBL) AS InvoiceCT, 
SUM(inv.TRAN_TOT_TXBL) AS InvoiceAMT, 
COUNT(inv.TRAN_PAID_AMT) AS PaymentCT, 
SUM(inv.TRAN_PAID_AMT) AS PaymentAmt, 
inv.CASH_CODE AS PaymentMethod, 
inv.TERMS_CD AS PayTerm,  
'' AS POCt, 
'' AS DPO, 
'' AS SourceSystem, 
contact.PHONE_NMBR AS 'Phone Number', 
contact.E_MAIL_ADDRESS AS 'E-mail', 
contact.FAX_NMBR AS 'Fax Number' 

FROM APINVOICE inv 
INNER JOIN APVENMAST mast ON mast.VENDOR = inv.VENDOR AND mast.VENDOR_GROUP =  inv.VENDOR_GROUP AND mast.VENDOR_STATUS ='A' 
INNER JOIN APVENADDR addr ON addr.VENDOR = mast.VENDOR AND (addr.CUR_ADDR='Y' AND addr.VENDOR_GROUP = mast.VENDOR_GROUP) 
INNER JOIN APCONTACT contact ON contact.VENDOR = mast.VENDOR AND contact.VENDOR_GROUP = mast.VENDOR_GROUP 
WHERE inv.INVOICE_DTE BETWEEN '1/1/2012' AND '12/31/2013' AND (inv.VENDOR_GROUP = '2' OR inv.VENDOR_GROUP = '35') 
GROUP BY mast.VENDOR,mast.VENDOR_VNAME,mast.TAX_ID,addr.ADDR1,addr.CITY_ADDR5,addr.STATE_PROV,addr.C OUNTRY,addr.POSTAL_CODE,addr.ADDR2,contact.PHONE_NMBR,contact.E_MAIL_ADDRESS,contact.FAX_NMBR,addr.LOCATION_CODE,inv.TERMS_CD,inv.CASH_CODE 
ORDER BY mast.VENDOR,mast.VENDOR_VNAME,mast.TAX_ID,addr.ADDR1,addr.CITY_ADDR5,addr.STATE_PROV,addr.COUNTRY,addr.POSTAL_CODE,addr.ADDR2,contact.PHONE_NMBR,contact.E_MAIL_ADDRESS,contact.FAX_NMBR,addr.LOCATION_CODE,inv.TERMS_CD,inv.CASH_CODE 

我越來越像結果

VendorID VendorName RemitID TIN Address1 Address2 City St Country Zip InvoiceCT InvoiceAMT PaymentCT PaymentAmt PaymentMethod PayTerm POCt DPO SourceSystem PhoneNumber E-mail FaxNumber 
    3 20 Company 1 INC     123456789   EAST STREET           WEST SIDE   NY         14787  9 0.00 9 30409.39 371                               
    3 20 Company 1 INC     123456789   EAST STREET           WEST SIDE   NY         14787  7 0.00 7 10128.22 371  PNOW   

填充列VendorIDVendorNameTinAddress1CityStZip InvoiceCTInvoiceAmtPaymentCTPaymentAmtPay Term

一切從這個例子還有空白

結果是給我需要的數字和一切,但我需要兩條線組合成1線和各的號應該加入到彼此給我是一個更大的總和。

我迷路了!

+0

我不知道它們是哪一列,但我還沒有讀過那個查詢,但只是略讀,在最下面的一行中有7個,你有9個在上面。這就是爲什麼DISTINCT沒有合併它們。他們是不同的行。 –

+0

這些是聚合字段,實際上,唯一的問題是第二行最右側的PNOW。 –

回答

1

兩行不同TERMS_CD,一個是PNOW,另一個是空白的,因爲你在該字段上分組,所以返回兩行。如果你拿到那個領域的最小/最大值,你會得到你想要的一行。

您必須決定哪些字段對您的情況中的不同值有貢獻。

+0

這有助於回答更大的問題。涉及的數據比我提交的數據多得多。謝謝 – gmalenko

1

你有兩行,因爲他們在PayTerm列有不同的價值觀

PayTerm blank/PNOW 

包括此列作爲某種聚集而不是原始列如最大(PayTerm)或 完全從查詢中排除它。

+0

InvoiceCT和PaymentCT已經是COUNT()。 –

+0

謝謝 - 編輯(和upvoted你的答案@Goat_CO) –