DISTINCT并没有删除欺骗

时间:2013-08-27 14:36:03

标签: tsql

我不确定如何以AB BA的方式使用DISTINCT。例如,我有两列BoughtLoyaltyProgramId,SoldLoyaltyProgramId。但即使我使用DISTINCT,当buyloyaltyprogramid中的相同代码出现在soldloyaltyprogramid中时,它也会产生重复。我不想欺骗,但我不知道它如何适用于多列和配对。

这是存储过程:

ALTER PROC AA
    @LPPProgramID UNIQUEIDENTIFIER ,
    @DateFrom DATETIME ,
    @DateTo DATETIME
AS 
SELECT DISTINCT TOP ( 5 )
        BoughtLoyaltyProgramId ,
        SoldLoyaltyProgramId ,
        DateTransactionCleared ,
        ExchangeRate
FROM    dbo.PEX_ClearedTransactions
WHERE   DateTransactionCleared >= @DateFrom
        AND DateTransactionCleared < @DateTo
        AND ( BoughtLoyaltyProgramId = @LPPProgramID
              OR SoldLoyaltyProgramId = @LPPProgramID
            )
ORDER BY ExchangeRate;

GO

3 个答案:

答案 0 :(得分:1)

唯一的是每个ROW,因此行中列中的值是不同的组合,数据不会在行的每一列中与该行中的其他列进行比较。

您可能还希望在列数据的Where语句中进行一些比较。

答案 1 :(得分:0)

以下是从两列中获取所有不同值的方法:

SELECT distinct * from
(SELECT BoughtLoyaltyProgramId
FROM dbo.PEX_ClearedTransactions
UNION ALL 
SELECT SoldLoyaltyProgramId
FROM dbo.PEX_ClearedTransactions) as A

答案 2 :(得分:0)

也许你想使用ROW_NUMBER

WITH cte 
     AS (SELECT boughtloyaltyprogramid, 
                soldloyaltyprogramid, 
                datetransactioncleared, 
                exchangerate, 
                RN=Row_number() OVER( 
                    partition BY boughtloyaltyprogramid, soldloyaltyprogramid 
                    ORDER BY exchangerate) 
         FROM   dbo.pex_clearedtransactions 
         WHERE  datetransactioncleared >= @DateFrom 
                AND datetransactioncleared < @DateTo 
                AND ( boughtloyaltyprogramid = @LPPProgramID 
                       OR soldloyaltyprogramid = @LPPProgramID )) 
SELECT TOP(5) * FROM   cte 
WHERE  RN = 1 
ORDER  BY exchangerate