0

我不确定如何以 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
4

3 回答 3

1

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

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

于 2013-08-27T14:38:50.737 回答
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 
于 2013-08-27T14:45:38.000 回答
0

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

SELECT distinct * from
(SELECT BoughtLoyaltyProgramId
FROM dbo.PEX_ClearedTransactions
UNION ALL 
SELECT SoldLoyaltyProgramId
FROM dbo.PEX_ClearedTransactions) as A
于 2013-08-27T14:39:46.817 回答