如何在存储过程中DISTINCT一列

时间:2013-09-27 05:35:00

标签: sql-server-2008 stored-procedures distinct

我写了一个存储过程。

我的要求是我必须显示数据,如果有任何列没有不同的Account_Names我必须显示像Account_Name:Multipul(varchar))

Create PROCEDURE [dbo].[OpenVendorBIllsSP] (@FromDate Date,@ToDate Date) 
AS 
BEGIN 
select
ROW_NUMBER() OVER(Order by vendor.VendorName ) AS ID,
PH.PurchasingHeaderID as No,
PH.TotalPriceCompanyCurrency as Balance,
acc.AccountName as [Account_Name],
PD.LineMemo as Memo,
from PurchasingHeader PH
LEFT OUTER JOIN TransactionType Trans ON PH.TransactionTypeID =Trans.TransactionTypeID
LEFT OUTER JOIN Vendor vendor on PH.VendorID=vendor.VendorID
LEFT OUTER JOIN PaymentTerm PT on PT.PaymentTermID = vendor.PaymentTermID
LEFT OUTER JOIN PurchasingDetail PD on PD.PurchasingHeaderID = PH.PurchasingHeaderID
LEFT OUTER JOIN Account Acc on Acc.AccountID= PD.FinancialAccountID 
where PH.TransactionTypeID=7
Group by vendor.VendorName,
PH.PurchasingHeaderID,PH.TotalPriceCompanyCurrency,acc.AccountName
END
GO

有了这个结果:

ID       No          Account_Name            Balance   Memo**
-------------------------------------------------------------
 101      VB1000        Cash-Petty Cash           4000.00  Memo
 102     VB1001        Accounts Receivable        5000.00  Memo
 103    VB1003       Cash-PettyCash             6000.00  Memo
 104     VB1003       Cash-PettyCash            6000.00  Memo
 105    VB1004        UndepositedFunds          7000.00  Memo

我需要这个结果:

ID      No        Account_Name          Balance    Memo
------------------------------------------------------
 101      VB1000      Cash-PettyCash        4000.00   Memo1
 102      VB1001      AccountsReceivable     5000.00   Memo2
 103     VB1003      ---Multiple----        6000.00   Memo3
 104     VB1004      UndepositedFunds      7000.00   Memo4

任何人都可以告诉我如何编写sp以获得结果。

编辑SP:

选择

ROW_NUMBER()OVER(按vendor.VendorName排序)AS ZID,

PH.PurchasingHeaderID为否,

PH.TotalPriceCompanyCurrency as Balance,

案例数量(PH.PurchasingHeaderID)> 1然后' Multipul'否则acc.AccountName END

来自PurchasingHeader PH的

LEFT OUTER JOIN TransactionType Trans ON PH.TransactionTypeID = Trans.TransactionTypeID

LEFT OUTER JOIN PH.VendorID = vendor.VendorID

上的供应商供应商

在PT.PaymentTermID = vendor.PaymentTermID

上的LEFT OUTER JOIN PaymentTerm PT

LEVE OUTER JOIN在PD.PurchasingHeaderID = PH.PurchasingHeaderID

上购买详情PD

LECE OUTER JOIN账户Acc.AccountID = PD.FinancialAccountID

其中PH.TransactionTypeID = 7

按供应商分组.VendorName,PH.PurchasingHeaderID,

PH.PurchasingHeaderID,PH.TotalPriceCompanyCurrency,acc.AccountName

1 个答案:

答案 0 :(得分:0)

你可以做一个包含所有内容的小节,然后是GROUP BY acc.AccountName, PH.TotalPriceCompanyCurrency等,并执行CASE WHERE COUNT(acc.AccountName) > 1