SQL查询:如果存在值,我需要两行

时间:2014-09-24 14:54:58

标签: sql sql-server

我有一个会计情况,我们在同一会计情况下支付(政策交易类型NBS)和负(政策交易类型取消或XLN)。我需要的行只有两个Tran Type' NBS'和' XLN'对于同一个客户。

示例数据:

    Client     PolicyNo  Revenue   TranType
   -------------------------------------------
    John Doe   Pol1234   1000.00     NBS
    John Doe   Pol1234  -1000.00     XLN
    Jane Loe   Pol5675   9000.00     NBS
    Jane Loe   Pol5676   8000.00     NBS
    Bill Foe   Pol0985   1000.00     NBS
    Bill Foe   Pol0987  -1000.00     XLN

查询只需返回前两行,因为Client和PolicyNo匹配,但也因为每一行都是NBS和XLN。如果同一客户的两条线路都是NBS,或者它们都是XLN,则需要将其排除在外。如果PolicyNo不匹配,则需要将其排除。

现在,我的查询返回完整集。 (为简单起见,我省略了上面示例中的一些列。

SELECT 
Company_1.Name, 
isnull(Customer.FirmNameCust, 
isnull(Customer.FirstName + ' ', '') +  isnull(Customer.LastName, '')) AS Client,
BasicPolInfo.PolNo,                            
DirectBillEntryHeader.StmtDate, 
irectBillEntryHeader.Description, 
DirectBillEntryDetail.*
FROM DirectBillEntryHeader 
INNER JOIN 
DirectBillEntryDetail 
ON DirectBillEntryHeader.DBEHId = DirectBillEntryDetail.DBEHId 
INNER JOIN BasicPolInfo 
ON DirectBillEntryDetail.PolId = BasicPolInfo.PolId 
INNER JOIN Customer 
ON DirectBillEntryDetail.CustId = Customer.CustId 
AND BasicPolInfo.CustId = Customer.CustId 
INNER JOIN Company 
ON DirectBillEntryDetail.WritingCoCode = Company.CoCode 
INNER JOIN Employee 
ON Customer.Prod1Code = Employee.EmpCode 
INNER JOIN Company Company_1 
ON Company.ParentCoCode = Company_1.CoCode
       WHERE (DirectBillEntryDetail.TranType = 'NBS') 
       AND (DirectBillEntryHeader.StmtDate >= DateAdd(DD, - 30, GETDATE())) 
       OR (DirectBillEntryDetail.TranType = 'XLN')
       AND (DirectBillEntryHeader.StmtDate >= DateAdd(DD, - 30, GETDATE()))

2 个答案:

答案 0 :(得分:1)

您可以使用EXISTS

SELECT t1.*
FROM dbo.TableName t1
WHERE t1.TranType IN('NBS','XLN')
AND EXISTS
(
    SELECT 1 FROM dbo.TableName t2
    WHERE t1.Client = t2.Client
      AND t1.PolicyNo = t2.PolicyNo
      AND t1.TranType <> t2.TranType
      AND t2.TranType IN('NBS','XLN')   
 )

答案 1 :(得分:0)

使用GROUP BY和HAVING查找具有这两种类型的所有客户端/策略。然后在你的from子句中使用它,这样你就只得到那些客户端/策略。

select ...
from
(
    select client, policyno 
    from mytable
    where trantype in ('NBS','XLN')
    group by client, policyno 
    having count(distinct trantype) = 2
) wanted
inner join sometable on sometable.client = wanted.client and sometable.policyno = wanted.policyno
...