不使用distinct,只选择1'控制编号'

时间:2014-08-27 19:14:05

标签: sql sql-server

我有这个查询

SELECT DISTINCT [CtrlNo]
,[RefNo]
,[DealNoCat]
,[tCustomer].[CustomerName]
,[tBank].BankName
,[tFIManagers].[FIName]
,[DaysOut]
,[FundDate]
,[Comment]
FROM [tContractsInTransit]
INNER JOIN tFIManagers
ON tFIManagers.FIManagerID = tContractsInTransit.FIManagerID
INNER JOIN tBank
ON tBank.BankID = tContractsInTransit.BankID
INNER JOIN tCustomer
ON tCustomer.CustomerID = tContractsInTransit.CustomerID
WHERE PFX = 'x'
AND Paid = 'false'
GROUP BY [CtrlNo]
,[RefNo]
,[DealNoCat]
,[tCustomer].[CustomerName]
,[tBank].BankName
,[tFIManagers].[FIName]
,[DaysOut]
,[FundDate]
,[Comment]
ORDER BY CtrlNo DESC

但是,这并没有给我我想要的结果,即使它完全按照我的要求去做。如果总共有10条记录,并且其中三条记录具有相同的CtrlNo,则如果RefNo和DaysOut之类的其他列之一不相同,则它将显示所有这三条记录。我需要显示那些具有最少DaysOut数量的三条记录。例如,如果DaysOut为2,6和48,则应显示带有2的记录。有没有办法做到这一点?提前致谢。

3 个答案:

答案 0 :(得分:2)

您希望不使用DISTINCT关键字并使用聚合函数。在这种情况下,MIN。 请注意' DaysOut'也从GroupBy子句

中删除
SELECT [CtrlNo]
,[RefNo]
,[DealNoCat]
,[tCustomer].[CustomerName]
,[tBank].BankName
,[tFIManagers].[FIName]
,MIN([DaysOut]) as Min_DaysOut
,[FundDate]
,[Comment]
FROM [tContractsInTransit]
INNER JOIN tFIManagers
ON tFIManagers.FIManagerID = tContractsInTransit.FIManagerID
INNER JOIN tBank
ON tBank.BankID = tContractsInTransit.BankID
INNER JOIN tCustomer
ON tCustomer.CustomerID = tContractsInTransit.CustomerID
WHERE PFX = 'x'
AND Paid = 'false'
GROUP BY [CtrlNo]
,[RefNo]
,[DealNoCat]
,[tCustomer].[CustomerName]
,[tBank].BankName
,[tFIManagers].[FIName]
,[FundDate]
,[Comment]
ORDER BY CtrlNo DESC

答案 1 :(得分:2)

假设最近新的sqlserver你可以使用像row_number()这样的窗口函数,如下所示:

SELECT ...
FROM (
    SELECT [CtrlNo]
    ,[RefNo]
    ,[DealNoCat]
    ,[tCustomer].[CustomerName]
    ,[tBank].BankName
    ,[tFIManagers].[FIName]
    ,[DaysOut]
    ,[FundDate]
    ,[Comment]
    , row_number() over (partition by CtrlNo order by DaysOut) as rn
    FROM [tContractsInTransit]
    INNER JOIN tFIManagers
        ON tFIManagers.FIManagerID = tContractsInTransit.FIManagerID
    INNER JOIN tBank
        ON tBank.BankID = tContractsInTransit.BankID
    INNER JOIN tCustomer
        ON tCustomer.CustomerID = tContractsInTransit.CustomerID
    WHERE PFX = 'x'
      AND Paid = 'false'
) as T
WHERE rn = 1;
ORDER BY CtrlNo DESC

答案 2 :(得分:0)

如果您使用的是SQL Server 2005或更高版本:

;WITH cte AS (
SELECT [CtrlNo]
,[RefNo]
,[DealNoCat]
,[tCustomer].[CustomerName]
,[tBank].BankName
,[tFIManagers].[FIName]
,[DaysOut]
,[FundDate]
,[Comment]
,ROW_NUMBER() OVER (Partition BY CtrlNo, ORDER BY DaysOut ASC) AS rn
FROM [tContractsInTransit]
INNER JOIN tFIManagers
ON tFIManagers.FIManagerID = tContractsInTransit.FIManagerID
INNER JOIN tBank
ON tBank.BankID = tContractsInTransit.BankID
INNER JOIN tCustomer
ON tCustomer.CustomerID = tContractsInTransit.CustomerID
WHERE PFX = 'x'
AND Paid = 'false'
)
SELECT * FROM cte
WHERE rn=1
ORDER BY CtrlNo DESC